<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gourav Raj on Medium]]></title>
        <description><![CDATA[Stories by Gourav Raj on Medium]]></description>
        <link>https://medium.com/@gogourav?source=rss-1ce810646b39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XBsfZB20TznKJ6nYlTXD5w.png</url>
            <title>Stories by Gourav Raj on Medium</title>
            <link>https://medium.com/@gogourav?source=rss-1ce810646b39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:11:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gogourav/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Object vs Map in JavaScript — When and Why?]]></title>
            <link>https://medium.com/@gogourav/object-vs-map-in-javascript-when-and-why-10847ed50eb8?source=rss-1ce810646b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/10847ed50eb8</guid>
            <category><![CDATA[javascript-object]]></category>
            <category><![CDATA[javascript-map]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[interveiws]]></category>
            <dc:creator><![CDATA[Gourav Raj]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 13:42:48 GMT</pubDate>
            <atom:updated>2024-09-21T13:42:48.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object vs Map in JavaScript — When and Why?</h3><p>As usual, let’s start with an output guess:</p><pre>const myself = {<br>    firstName: &#39;Gourav&#39;,<br>}<br><br>const platform = {<br>    name: &#39;medium&#39;<br>}<br><br>const agg = {};<br><br>agg[myself] = &#39;This is about myself&#39;;<br>agg[platform] = &#39;This is medium platform&#39;;<br><br>console.log(agg[myself]);</pre><p>The output is:</p><pre>This is medium platform</pre><p>Strange huh? The one-sentence reason is that JS Objects store keys as strings, which converts the key value (whatever is supplied) to a string.</p><p>And what is the string representation of an object data type? <br>Since an object is a reference type its string representation is [object Object] .</p><p>So, the mentioned agg object looks like this:</p><pre>{<br>  &#39;[object Object]&#39; : &#39;This is medium platform&#39;<br>}</pre><p>Now what’s an alternative to object in a scenario where we need to deal with non-string key data types? <br><strong><em>MAP</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*xtYFbb7z5qNZsWPDspcT1g.png" /><figcaption>Object vs Map in Javascript</figcaption></figure><p>Let’s understand why one should prefer map over objects:</p><p>1. Key Types</p><ul><li><strong>Objects</strong>: Keys are always strings or symbols. If you try to use other types (like numbers, objects, etc.), they will be converted to strings.</li><li><strong>Maps</strong>: Keys can be of any type — primitive values (numbers, strings) or object references. This makes Map more versatile when you need non-string keys.</li></ul><p><strong>Example</strong>:</p><pre>const obj = {};<br>obj[{}] = &quot;value&quot;;  // Key becomes &quot;[object Object]&quot;<br>const map = new Map();<br>map.set({}, &quot;value&quot;);  // The key is the actual object reference</pre><h3>2. Key Ordering</h3><ul><li><strong>Objects</strong>: Keys are unordered, though modern JavaScript engines tend to iterate them in the order they were added. However, this behavior is not guaranteed and can sometimes be inconsistent.</li><li><strong>Maps</strong>: Keys maintain their insertion order. If you iterate over a map, keys will always appear in the order they were inserted.</li></ul><h3>3. Performance</h3><ul><li><strong>Maps</strong>: Are often faster when adding, deleting, or checking the existence of many key-value pairs, especially when the keys are not strings. Maps are optimized for these operations.</li><li><strong>Objects</strong>: These are not specifically optimized for frequent key-value operations, especially with non-string keys. Objects are traditionally used as lightweight key-value stores, but as they grow, performance can degrade compared to maps.</li></ul><h3>4. Size</h3><ul><li><strong>Objects</strong>: You have to manually track the size of an object if you need to know how many keys it contains, using Object.keys(obj).length, which can be inefficient for large objects.</li><li><strong>Maps</strong>: Have a size property that provides the number of entries directly without needing any computation.</li></ul><p><strong>Example</strong>:</p><pre>const map = new Map();<br>map.set(&#39;a&#39;, 1);<br>console.log(map.size);  // 1</pre><h3>5. Built-in Methods</h3><ul><li><strong>Objects</strong>: Lack built-in methods for managing key-value pairs, requiring you to use Object.keys(), Object.values(), Object.entries(), and manual loops for most operations.</li><li><strong>Maps</strong>: Come with a rich set of methods for working with entries (set, get, delete, has, clear, etc.) as well as built-in iteration support (e.g., forEach, entries, keys, values).</li></ul><p><strong>Example</strong>:</p><pre>const map = new Map();<br>map.set(&#39;key1&#39;, &#39;value1&#39;);<br>map.set(&#39;key2&#39;, &#39;value2&#39;);<br>map.forEach((value, key) =&gt; {<br>  console.log(key, value);<br>});</pre><h3>6. Prototype Inheritance</h3><ul><li><strong>Objects</strong>: Are subject to prototype inheritance, which means they have default properties and methods (like toString, hasOwnProperty, etc.). This can sometimes lead to issues if you&#39;re unaware of certain inherited properties.</li><li><strong>Maps</strong>: Have no such prototype inheritance for their keys, making them “cleaner” if you want to avoid accidental interference with inherited properties.</li></ul><p><strong>Example</strong>:</p><pre>const obj = {};<br>console.log(obj.hasOwnProperty(&#39;toString&#39;));  // true<br>console.log(obj[&#39;toString&#39;]);  // The toString method<br>const map = new Map();<br>console.log(map.has(&#39;toString&#39;));  // false</pre><h3>7. Intent and Semantics</h3><ul><li><strong>Objects</strong>: Are mainly used to represent data structures or entities with known properties.</li><li><strong>Maps</strong>: Are explicitly designed for dynamic key-value pairs, making your intent clearer when using them to store arbitrary key-value data.</li></ul><h3>When to Use Object and when to use a Map:</h3><p><strong>Use an Object</strong> <strong>when</strong></p><ul><li>You need a simple structure to represent a well-defined data model or entity.</li><li>Your keys will always be strings or symbols.</li><li>Performance is not a concern for frequent addition or deletion of properties.</li></ul><p><strong>Use a Map</strong> <strong>when</strong></p><ul><li>You need to use non-string keys (e.g., objects, functions).</li><li>You require frequent key-value operations and care about performance.</li><li>You need to preserve the insertion order of keys.</li><li>You want built-in methods and clearer semantics for a dynamic key-value store.</li></ul><p>References:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10847ed50eb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Less Known Microtask Queue in JavaScript]]></title>
            <link>https://medium.com/@gogourav/less-known-microtask-queue-in-javascript-cae2189770d9?source=rss-1ce810646b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/cae2189770d9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[single-threaded]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[Gourav Raj]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 10:55:38 GMT</pubDate>
            <atom:updated>2024-09-07T14:48:19.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start with some output guess first:</p><pre>setTimeout(() =&gt; {<br>  console.log(&#39;Timeout callback&#39;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&#39;Promise callback&#39;);<br>});</pre><p>What do you think the output would be? Well, the output is</p><pre>Promise callback<br>Timeout callback</pre><p>But why?</p><p>This brings out a very important concept in JavaScript programming, Microtask Queue.</p><p>The event loop is a mechanism in JavaScript that is responsible for handling asynchronous code in your program. It is an endless loop that looks for the call stack and when empty deques asynchronous tasks and pushes it to the call stack.</p><p>There are two callback queues or task queues from which the tasks are dequeued:</p><ol><li>Macrotask Queue</li><li>Microtask Queue</li></ol><p>Both the above queues hold the callbacks waiting to be executed after an asynchronous operation. The difference between these two queues is the type of callbacks that they enqueue.</p><p>The Microtask queue holds the tasks that are imperative like promise callbacks, and mutation observer API callbacks whereas the Macrotask queue holds the tasks that are relatively less important like the timer callbacks, UI rendering, etc.</p><p>The Event Loop gives the Microtask queue more priority over microtask queues. This means the event loops complete all the tasks present in the microtask queue before executing any microtask queue items.</p><p>Now, in the above example according to the definition, after the execution of the synchronous code, the state of the queues is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*5KPwEXsTuY0sFA096kfQVg.png" /><figcaption>Microtask Queue</figcaption></figure><p>Both the callbacks are available to the event loop to execute but since the microtask queue has greater priority than macrotask, the promise callback is executed first, and then the setTimeout callback.</p><p>Reference: <a href="https://javascript.info/event-loop#macrotasks-and-microtasks">https://javascript.info/event-loop#macrotasks-and-microtasks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cae2189770d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Klaviyo System Design]]></title>
            <link>https://medium.com/@gogourav/klaviyo-system-design-b09911781335?source=rss-1ce810646b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/b09911781335</guid>
            <category><![CDATA[email-marketing]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[email-automation-tool]]></category>
            <category><![CDATA[klaviyo-email-marketing]]></category>
            <dc:creator><![CDATA[Gourav Raj]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 19:40:26 GMT</pubDate>
            <atom:updated>2024-06-03T19:59:50.591Z</atom:updated>
            <content:encoded><![CDATA[<p>Klaviyo is a leading marketing automation platform that empowers businesses to create personalized email and SMS campaigns using advanced customer data integration and analytics.</p><p>With over a few hundred thousand customers, Klaviyo’s platform manages billions of emails and SMS messages daily. Let’s delve into the system behind Klaviyo that enables it to operate at this impressive scale.</p><h3><strong>System Requirements</strong></h3><p>Before we dive deep into the design, let’s establish the fundamental requirements that Klaviyo offers.</p><p><strong>Functional Requirements</strong></p><ul><li>List Growth via Sign-Up Forms: The platform captures email and phone subscriptions from customers’ websites.</li><li>Campaigns: Customers execute campaigns targeting the marketing subscribers.</li><li>Triggers and Flows: Customers create and implement flows that respond to triggers.</li></ul><p><strong>Non-Functional Requirements</strong></p><ul><li>High availability</li><li>Low latency</li><li>Reliability</li><li>Fault Tolerant</li></ul><h3><strong>Estimation</strong></h3><p>Let’s estimate some statistics to gauge Klaviyo’s scale. The numbers below are taken as averages and are rounded off for easier understanding.</p><p>Total customers = 150,000 (<a href="https://investors.klaviyo.com/news/news-details/2024/Klaviyo-Announces-Fourth-Quarter-and-Fiscal-Year-2023-Financial-Results/default.aspx#:~:text=Recent%20Business%20Highlights%3A&amp;text=Over%20143%2C000%20customers%20are%20using,end%20of%20fiscal%20year%202022.">source</a>)<br>Total profiles per customer = 100,000 (let’s say)<br>Total profiles across all the customers = 150,000*100,000 = 15 Billion<br>Daily active profiles = 10% of total profiles = 1.5 Billion (let’s say)</p><p><strong>List Growth</strong></p><p>Assuming 10% of the daily active profiles subscribe to the marketing list on the website,</p><p>Total number of profile subscription = 1.5 B * 0.1 / day = <strong>1800 / sec</strong></p><p><strong>Campaigns</strong></p><p>Let’s assume that campaigns are sent to only 25% of all the customer profiles available. Therefore,</p><p>Number of campaigns per Klaviyo customer = 2 / week (<a href="https://academy.klaviyo.com/page/increase-sales-with-campaigns#:~:text=Top%20performing%20brands%20on%20Klaviyo,and%20start%20increasing%20sales%20today.&amp;text=Learn%20how%20to%20use%20the,streamline%20your%20content%20creation%20process.">source</a>)</p><p>Number of profiles reached by a campaign per Klaviyo customer = 2*0.25*100000 / week = 50,000 / week = 7000 / day</p><p>Number of profiles reached by campaigns across all Klaviyo customers = 7,000*150,000 = 1050 M / day = <strong>12600 profiles / sec</strong></p><p><strong>Flows and Events</strong></p><p>Suppose an event is generated for every other profile among all the daily active profiles. Therefore,</p><p>Total events generated = 1.5*0.5 B / day = 750 M / day =<strong> 9000 events / sec</strong></p><h3>High-Level Design</h3><p>Let’s individually explore the high-level designs of the three mentioned functional requirements and understand each component.</p><h3><strong>List Growth</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*uSBK1gW1l2ZlNgPusFN7lA.jpeg" /><figcaption>Klaviyo List Growth System Design</figcaption></figure><ul><li>Klaviyo’s JavaScript script captures and submits email and phone numbers for users via an API on the customer’s website.</li><li>The API then submits the captured data to the API server via the load balancer.</li></ul><pre>POST https://a.klaviyo.com/client/profile?company_id=&lt;public-api-key&gt;<br>BODY email, phone_number , timestamp</pre><ul><li>The API server responds with a 202 status code and enqueues the message into a message queue (e.g.,<em> Kafka, RabbitMQ</em>).</li><li>The <em>Profile Servic</em>e is responsible for managing profiles and inserting them into a database. The choice of database is NoSQL, such as <em>MongoDB</em>, as strict consistency requirements are not necessary. Additionally, it is easily scalable. The collection schema is as follows:</li></ul><pre>{<br>  &quot;_id&quot;: &quot;ObjectId&quot;,<br>  &quot;userId&quot;: &quot;int&quot;, <br>  &quot;listId&quot;: &quot;string&quot;,<br>  &quot;email&quot;: &quot;string&quot;,  <br>  &quot;emailSubscribed&quot;: &quot;boolean&quot;,  <br>  &quot;phoneNumber&quot;: &quot;string&quot;,  <br>  &quot;phoneNumberSubscribed&quot;: &quot;boolean&quot;,  <br>  &quot;createdAt&quot;: &quot;ISODate&quot;, <br>  &quot;updatedAt&quot;: &quot;ISODate&quot; <br>}</pre><h3><strong>Campaigns</strong></h3><p>A campaign is scheduled by Klaviyo users for a list of profiles. It is scheduled for a specific date and time and runs at the configured time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCk0DWXiOTEdFvfv1oNRcA.jpeg" /><figcaption>Klaviyo Campaigns System Design</figcaption></figure><ul><li>When a campaign is created, it is directly inserted into the database via the API server.</li></ul><pre>  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),<br>  name VARCHAR(255) NOT NULL,<br>  status VARCHAR(255) NOT NULL CHECK (&quot;status&quot; IN (&#39;sent&#39;, &#39;unsent&#39;)),<br>  list_id VARCHAR(255) NOT NULL,<br>  template_id VARCHAR(255) NOT NULL,<br>  scheduled_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,    // indexed<br>  created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,<br>  updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,</pre><ul><li>After being stored, the campaign can be run immediately or after a certain amount of delay. Therefore, the <em>Campaign Scheduler Service</em> queries the database for the document with the most recent <em>scheduled_at</em> key and queues it to a message queue.</li><li>The table has an index on <em>scheduled_at </em>for faster retrieval.</li><li>The chosen database is SQL, as each operation is treated as a transaction, and ACID properties are preferred. However, NoSQL databases are also a viable option.</li><li>The <em>Campaign Executor Service</em> dequeues a message from the queue and queries the database for all the profiles associated with the campaigns. It creates an individual message for every profile and enqueues it into the delivery system queue.</li><li>The <em>Delivery System Queue</em> dequeues a message and retrieves information about the templates and the images of the message. For storing media such as images or GIFs, S3 or Azure Blob storage is used.</li><li>Depending on the channel, an API request is made to the <em>Twilio</em> or <em>SendGrid</em> service, and the profile receives the communication.</li></ul><h3><strong>Trigger and Flows</strong></h3><p>A flow created by a Klaviyo user is executed whenever a trigger is received. This trigger can be either a built-in trigger or one posted by third-party integrations, such as Shopify, via the admin APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ec29p7_mdvJOryjqQJeHYQ.jpeg" /><figcaption>Klaviyo Trigger Flow System Design</figcaption></figure><ul><li>When an event is triggered, it is recorded in the database (A) and enqueued into a message queue. If the profile is new, it is created and stored in the profile collection.</li><li>The <em>Trigger Processor Service</em> retrieves all active flows associated with the trigger and enqueues a message into another queue.</li><li>The enqueued message is retrieved by the <em>Flow Executor Service</em> and stored in the database (B).</li></ul><pre>id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),<br>trigger_name VARCHAR(255) NOT NULL, <br>flow_id VARCHAR(255) NOT NULL,<br>profile_id VARCHAR(255) NOT NULL,<br>status VARCHAR(15) NOT NULL,<br>run_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,       //indexed<br>created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,<br>updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL</pre><ul><li>The <em>Action Runner</em> picks the entry with the shortest <em>run_at</em> value and executes it. If there is no delay in the flow, the action (email or SMS) is executed and a message is enqueued into the delivery system queue. If there is a delay, the flow service performs actions (email or SMS send) before the delay and updates the <em>run_at</em> value of the record.</li><li>The table has an index on <em>run_at </em>for faster retrieval.</li><li>The chosen database is SQL, as each operation is treated as a transaction, and ACID properties are preferred. However, NoSQL databases are also a viable option.</li><li>The <em>Delivery System</em> receives the messages and delivers the email or SMS to the profile.</li></ul><p>If you’ve made it this far in reading, it means you found this blog helpful or interesting. Please show your support by giving it a clap 🙏🏼.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b09911781335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Argument Passing in JavaScript Functions]]></title>
            <link>https://medium.com/@gogourav/understanding-argument-passing-in-javascript-functions-9b1c49b8d0bd?source=rss-1ce810646b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1c49b8d0bd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[call-by-value]]></category>
            <category><![CDATA[interesting]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Gourav Raj]]></dc:creator>
            <pubDate>Thu, 23 May 2024 14:02:23 GMT</pubDate>
            <atom:updated>2024-05-23T14:15:23.735Z</atom:updated>
            <content:encoded><![CDATA[<p>We all think that objects and functions are passed as references in JavaScript but is that correct? 🤔</p><p>Let’s learn from this example.</p><p>Here is a code snippet where an object (obj) is passed to a function foo which tries to manipulate the object&#39;s value.</p><pre>function foo(obj){<br>  obj = { value : &#39;changed&#39; }<br>};<br><br>const obj = { value: &#39;unchanged&#39; };<br><br>foo(obj);<br>console.log(obj);</pre><p>What do you think the value would become? Would it be altered or not?<br>Interestingly, it will not change.</p><p>Why not??</p><p>This is because <strong>In JavaScript function arguments are passed as values and not references.</strong></p><pre>{ value: &#39;unchanged&#39; }</pre><p>But, this example tells a different story.</p><pre>function foo(obj){<br>  obj.value =&#39;changed&#39;;<br>};<br><br>const obj = { value: &#39;unchanged&#39; };<br><br>foo(obj);<br>console.log(obj);</pre><pre>{ value: &#39;changed&#39; }</pre><p>If it’s passed by value then how come the value got changed?</p><p>This is because although the arguments are passed as value, the value itself is a reference.</p><p>This means the function gets a copy of the reference of the object and updating does not have any effect on the original object.</p><p>Let’s understand further using a C++ example:</p><p>Look at this code</p><pre>void foo1(int* arr) {<br> arr[0] = 1;<br>}<br><br>void foo2(int* arr) {<br> int arr1[1] = {2};<br> arr = arr1;<br>}<br><br>int main() {<br><br> int arr[1] = {0};<br><br> foo1(arr);<br> cout &lt;&lt; arr[0] &lt;&lt; &quot;\n&quot;;<br><br> foo1(arr);<br> cout &lt;&lt; arr[0];<br><br> return 0;<br>}</pre><pre>1<br>1</pre><p>As you can see, in both the functions (foo1 and foo2) the argument arr acts as a copy of a pointer pointing to the array. Therefore one can manipulate the value pointed by the array but cannot change the original pointer to point to a different array.</p><p>I hope this was interesting. Please support if you enjoyed it. 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*AHjNytD7yJ8S3xGb8b2D-w.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1c49b8d0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>