<?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 Rohit Lakhotia on Medium]]></title>
        <description><![CDATA[Stories by Rohit Lakhotia on Medium]]></description>
        <link>https://medium.com/@rohitlakhotia?source=rss-e4cf57fe9df6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LhUkhZX8PD7YPSNTl6qgkg.jpeg</url>
            <title>Stories by Rohit Lakhotia on Medium</title>
            <link>https://medium.com/@rohitlakhotia?source=rss-e4cf57fe9df6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:08:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohitlakhotia/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[How Dropbox scaled its storage infrastructure?]]></title>
            <link>https://medium.com/@rohitlakhotia/how-dropbox-scaled-its-storage-infrastructure-e9126970cd60?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9126970cd60</guid>
            <category><![CDATA[dropbox]]></category>
            <category><![CDATA[scale]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 06:51:02 GMT</pubDate>
            <atom:updated>2026-09-25T05:47:56.794Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Dropbox scaled its storage infrastructure with a custom-built system called Magic Pocket, utilizing high-density SMR drives and advanced data replication for durability and scalability.</h4><p>Have you ever wondered how Dropbox manages to sync and store millions of files for over 700 million users? In today’s digital world, users store everything digitally, from college documents to business documents to even family photos. Dropbox’s infrastructure is built in such a way that it can handle vast amounts of data reliably and securely. Let’s discover how Dropbox manages to achieve this in this blog today.</p><h4>What is Dropbox?</h4><p>Dropbox is a <strong>file hosting service. </strong>It allows users to store all of their files in one place by making a special folder on the user’s computer. The contents of these folders are uploaded and synchronized to Dropbox’s servers as well as other computers and devices on which the user has installed Dropbox.</p><p>Dropbox uses a <a href="https://en.wikipedia.org/wiki/Freemium?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure">freemium</a> <a href="https://en.wikipedia.org/wiki/Business_model?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure">business model</a><strong>,</strong> where users can sign up for a free account with a limited storage capacity, with optional paid subscriptions providing additional storage and features.</p><p>Any Dropbox Basic consumer gets <strong>2 GB of free storage spac</strong>e when they sign up. Dropbox Plus subscribers get<strong> 2 TB of storage space</strong> in addition to other benefits.</p><h4>As we all know, “Necessity is the mother of invention” and that’s what led to the invention of Dropbox!</h4><p>When Dropbox’s founder <strong>Drew Houston</strong> was a student at MIT, he was constantly forgetting his <strong>USB flash drive</strong>, so he came up with the idea for Dropbox. At first, he created it for his own use, but he soon realized that those with similar problems might profit from it as well.</p><p>He formed <strong>Evenflow</strong> (which is also the company behind Dropbox), in <strong>May 2007</strong> and obtained Y Combinator seed funding shortly after. It was renamed as Dropbox in October 2009.</p><p>Dropbox’s user base grew steadily after its launch. In<strong> April 2009,</strong> it surpassed<strong> 1 million</strong> registered users, rising to <strong>2 million in September</strong> and<strong> 3 million in November</strong>. Now in<strong> 2024 </strong>it has over <strong>700 million</strong> registered users.</p><h4>Dropbox’s High-level Architecture</h4><h4>In 2007</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*cdXqStePCO2wGGg7" /></figure><p>This was running the<a href="https://en.wikipedia.org/wiki/Application_server?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure"> application servers</a>, <a href="https://en.wikipedia.org/wiki/Web_server?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure">web servers</a> that was serving static content, it was also running MYSQL and storing all data that anyone was putting on Dropbox on his local discs.</p><p>Problem: The servers ran out of disk space so they had to put the data somewhere else.</p><p>So, they chose to put all the data on the<strong> Amazon’s S3 </strong>and they decided to move to <strong>MYSQL </strong>instance to a different box so that they could be separated and run on separate hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*I_fLsPHzav0OlfNu" /></figure><p>One thing to notice here is this arrow is unidirectional, that means the clients are only hitting the server. So when the new changes that happen, the client has to hit the server again (that’s called Polling). The client has to poll the server every now and then and that’s usually a bad thing!</p><p>Thus, they came up with this new idea!</p><h4>Early 2008</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*rjZA_QoMtbVMUiPl" /></figure><p>This new service called the <strong>NotServer (short for Notification Server) </strong>smoothened client interactions by actively pushing notifications to them, ensuring real-time updates. The server was split into two web servers, one running in managed hosting and one running in AWS.</p><ul><li><strong>AWS: </strong>Hosting all the file content and accepting all the uploads.</li><li><strong>Managed Hosting: </strong>Doing all the metadata calls so they are called meta servers or block servers.</li></ul><h4>Late 2008</h4><p>As Dropbox grew, it has to change its architecture to address the performance issues. Three of those major changes are:</p><ol><li><strong>Scaling Meta and Block Servers</strong><br>Dropbox had a single meta server and block server. As a part of scaling, more of these servers have to be added but also required careful load balancing to ensure reliability and performance.</li><li><strong>Addressing Latency in Database Queries</strong><br>From the diagram one can notice, the block servers initially made direct database calls, creating significant latency due to long-distance round trips between AWS in Virginia and the managed hosting cluster in Texas. <br>To resolve this, Dropbox shifted to using <strong>RPCs </strong><a href="https://en.wikipedia.org/wiki/Remote_procedure_call?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure"><strong>(Remote Procedure Calls)</strong></a> between block servers and meta servers. This allowed meta servers to handle database queries internally, reducing latency and centralizing logic for efficiency.</li><li><strong>Database Scaling</strong><br>Dropbox faced challenges with having a single database. Traditional solutions like sharding or partitioning were options, but they opted for a simpler approach by implementing <strong>memcache for caching</strong>.</li></ol><p>In this way, they ended up with the below architecture at launch!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*haLcDEkpQvdQTUrs" /></figure><p>They added a bunch of meta servers and block servers, put a load balancer tier in front of meta servers and added a memcache too. The block servers now do rpcs to the load balancers.</p><h4>In 2012</h4><p>The architecture in 2012 is pretty much same, just the difference is, everything is filled out with even more enormous data!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ng1wLH6Rg9WivBoA" /></figure><h4>Further challenges and enhancements:</h4><ul><li><strong>Load Balancing</strong><br>Scaling load balancers was challenging due to<a href="https://www.geeksforgeeks.org/what-is-the-python-global-interpreter-lock-gil/?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure"> Python’s Global Interpreter Lock (GIL</a>), which limited parallel request handling. Dropbox addressed this by pairing each load balancer with a <a href="https://www.hitechnectar.com/blogs/hot-backup-vs-cold-backup/?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure">hot backup</a> for failover, achieving high availability without building custom software.</li><li><strong>Notification Server (NotServer)</strong><br>The NotServer, designed to push real-time updates to clients, managed <strong>tens of millions of simultaneous connections</strong>. Due to firewalls, clients initiated connections, allowing NotServer to send notifications through these open channels. <br>To manage this scale, Dropbox implemented a <strong>two-layer hierarchy</strong>: <em>a primary layer distributed notifications to multiple NotServers, which in turn managed client connections thus and ensured high throughput.</em></li></ul><h4>Dropbox workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ZaTSC6_E3Vprfsc9" /><figcaption><a href="https://blog.dropbox.com/topics/product-tips/dropbox-for-business-security-whitepaper?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-54-how-dropbox-scaled-its-storage-infrastructure">How does Dropbox for Business protect your data? [Whitepaper] | Dropbox Blog</a></figcaption></figure><h4>User Interaction (Bottom Layer)</h4><ul><li><strong>Devices:</strong> Users interact with Dropbox via devices like desktops, tablets, or smartphones. These devices act as the entry points for uploading, downloading, or modifying files stored in Dropbox.</li><li><strong>SSL Layer:</strong> All communication between the user’s device and Dropbox’s servers is encrypted using Secure Sockets Layer (SSL). This ensures that data in transit cannot be intercepted or tampered with, providing a secure connection.</li></ul><p><strong>Workflow:</strong></p><ul><li>When a user uploads a file, the request is sent securely to Dropbox’s infrastructure through the SSL layer.</li><li>Similarly, when a user accesses a file, a request is sent to fetch the data from storage and metadata servers.</li></ul><h4>Processing Servers (Middle Left Layer)</h4><p><strong>Purpose:</strong> This layer is responsible for preparing the data for secure storage or retrieval. It handles encryption, integrity checks, and other application-specific processing tasks.</p><ul><li><strong>Encryption and Application Services:</strong></li><li>Files are encrypted here to enhance security. Encryption ensures that even if someone accesses the storage server, the raw data cannot be read without decryption keys.</li><li>Application services include:</li><li><strong>Deduplication</strong>: Identifying duplicate files to optimize storage.</li><li><strong>File Chunking</strong>: Splitting large files into smaller blocks for efficient storage and retrieval.</li></ul><p><strong>Workflow:</strong></p><ul><li>Once the file is processed, it is sent to the <strong>Storage Servers</strong> for saving the actual data or the <strong>Metadata Servers</strong> for managing file-related information.</li></ul><h4>Storage Servers (Top Left Layer)</h4><p><strong>Purpose:</strong> This is where the actual file data is stored.</p><ul><li><strong>File Blocks:</strong> The file data is broken into <strong>encrypted blocks</strong>. These blocks are stored independently, making it highly secure and scalable.</li><li><strong>Scalability and Fault Tolerance:</strong> Storing files as encrypted blocks allows Dropbox to distribute data across multiple servers and data centers, ensuring reliability and redundancy.</li></ul><p><strong>Workflow:</strong></p><ul><li>Files processed by the middle layer are stored here in a secure, distributed manner.</li><li>When users request files, the encrypted blocks are retrieved, reassembled, and sent back to the user’s device.</li></ul><h4>Metadata Servers (Top Right Layer)</h4><p><strong>Purpose:</strong> While storage servers manage the file data, metadata servers handle all the descriptive information about the files. This separation allows faster lookups and efficient operations.</p><ul><li><strong>Metadata Service:</strong> Stores essential details about each file, such as:</li><li><strong>File Name</strong></li><li><strong>Location in the user’s folder structure</strong></li><li><strong>Last modified date</strong></li><li><strong>File type and size</strong></li><li><strong>Database:</strong> The metadata is maintained in databases that ensure fast access and updates.</li><li><strong>Notification Service:</strong> Tracks file changes (e.g., uploads, deletions, or edits) and triggers notifications for syncing across user devices.</li></ul><p><strong>Workflow:</strong></p><ul><li>When a user uploads or modifies a file, the metadata is updated in the database.</li><li>Notifications are sent to devices linked to the user’s account, ensuring all devices stay synchronized.</li></ul><h4>Data Flow Across Layers</h4><ul><li><strong>Upload/Write Operation:</strong></li></ul><ol><li>The user uploads a file via their device, and the request is encrypted by the SSL layer.</li><li>The file is processed by the <strong>Processing Servers</strong>, where it’s encrypted and prepared for storage.</li><li>The processed file is stored as encrypted blocks in the <strong>Storage Servers</strong>.</li><li>Metadata about the file is sent to the <strong>Metadata Servers</strong>, where it is stored in the database.</li></ol><ul><li><strong>Download/Read Operation:</strong></li></ul><ol><li>The user requests a file via their device, and the request passes through the SSL layer to Dropbox’s servers.</li><li>The <strong>Metadata Servers</strong> are queried to locate the file in the storage system.</li><li>The encrypted blocks of the file are retrieved from the <strong>Storage Servers</strong>.</li><li>The blocks are decrypted and reassembled by the <strong>Processing Servers</strong> before being sent to the user.</li></ol><h4>One of Dropbox’s most fascinating features is its ability to sync files across devices quickly and efficiently due to an optimized sync protocol. Here’s how it works:</h4><p>Dropbox syncs files by dividing them into <strong>4MB </strong>chunks, each with a <strong>unique identifier (hash)</strong>. When a file changes, Dropbox only uploads the updated chunks, reducing data transfer. Additionally, Dropbox uses <strong>binary diff</strong>, sending only the difference between old and new chunks, further reducing data transfer.</p><p>Dropbox also employs <strong>deduplication</strong> to store only one copy of a file if it’s uploaded multiple times, saving space and bandwidth.</p><h4>Challenges Dropbox faced:</h4><ul><li><strong>High Costs:</strong> Hosting data on AWS was becoming expensive as Dropbox scaled, with each additional petabyte adding significant costs.</li><li><strong>Dependency on Third-Party: </strong>Using third-party servers restricted Dropbox’s control over security, reliability, and customization.</li><li><strong>Scaling Servers</strong>: Difficulty in scaling meta and block servers while ensuring performance and reliability.</li><li><strong>Syncing Large Data</strong>: Efficiently syncing and handling large data volumes across multiple devices.</li><li><strong>High Consistency</strong>: Maintaining high consistency with memcache and ensuring seamless database scaling.</li><li><strong>Performance Limitations:</strong> As Dropbox grew, AWS struggled to fully support its unique storage and access requirements.</li></ul><h4>Solutions adopted by Dropbox</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*5xfuuaW86lInV34j" /></figure><ol><li>Moving from AWS to Custom Infrastructure</li><li><a href="https://medium.com/gitconnected/how-did-magic-pocket-help-dropbox-save-millions-2f744c643194">Building Magic Pocket</a></li><li>Using a Hybrid Model</li><li>Shingled Magnetic Recording (SMR) Drives</li><li>Adding Cold Storage for Older Data</li></ol><p>You can view this <a href="https://medium.com/gitconnected/how-did-magic-pocket-help-dropbox-save-millions-2f744c643194">here</a></p><p>By now, you must have had a clear idea of<strong> How Dropbox scaled its storage infrastructure.</strong> In a nutshell, Dropbox efficiently syncs and stores files for over 700 million users by using a custom-built infrastructure, optimized sync protocol, and strategic use of cloud services. Dropbox scaled its storage infrastructure with a custom-built system called Magic Pocket, utilizing high-density SMR drives and advanced data replication for durability and scalability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9126970cd60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is ⁠PostgreSQL?]]></title>
            <link>https://blog.devgenius.io/what-is-postgresql-36b1c26c1405?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b1c26c1405</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 17:51:35 GMT</pubDate>
            <atom:updated>2024-12-07T17:51:35.797Z</atom:updated>
            <content:encoded><![CDATA[<h4>PostgreSQL is a robust, open-source object-relational database system known for advanced features, scalability, and support for complex queries.</h4><p>Have you ever wondered what makes modern applications so reliable and efficient in handling vast amounts of data? Behind the scenes of many data-driven services lies a robust <strong>Relational Database Management System (RDBMS). </strong>One standout in this field is <strong>PostgreSQL</strong>, an open-source powerhouse renowned for its <strong>reliability, scalability</strong>, and advanced features. Whether you’re developing a web application, managing a data warehouse, or exploring IoT solutions, PostgreSQL offers a versatile and powerful platform that meets diverse needs. Let’s discover more about <strong>PostgreSQL</strong> in this blog today.</p><p><strong>PostgreSQL </strong>is one of the most trusted names in <strong>open-source relational databases</strong>. Its development started back in <strong>1986 </strong>at <strong>UC Berkeley</strong> under <strong>Michael Stonebraker</strong>.</p><p><em>Like other relational databases, it stores data in tables with columns and rows and uses SQL (Structured Query Language) to read and write data.</em></p><p>PostgreSQL is technically an <strong>object-relational database</strong>, meaning:</p><ul><li>It can create custom data types to store objects with properties</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Du_wMAmXTwyAWfBd" /></figure><ul><li>Supports advanced features like inheritance and polymorphism.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Fhopq5D5y4Fj0kRf" /></figure><p>When writing data, PostgreSQL uses fully <strong>ACID-compliant transactions</strong> to ensure data integrity. It also features <strong>Multi-Version Concurrency Control (MVCC)</strong>, which allows multiple transactions to run simultaneously by giving each one a snapshot of the database, preventing traffic jams or locks.</p><blockquote>Developers love PostgreSQL for its <strong>extensibility</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ovrqa-M8X6GEN6uH" /></figure><p>You can reuse queries by writing <strong>stored procedures</strong>, and it supports languages beyond SQL, such as <strong>Python and C.</strong> PostgreSQL has a robust ecosystem of extensions like <strong>PostGIS for geospatial data</strong> used by apps like <strong>Uber, </strong>and <strong>Citus</strong> for scaling and distributing the database, and <strong>PGEmbedding</strong> for giving AI chatbots long-term memory. To get started, you can download and install <a href="https://www.postgresql.org/?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-32-what-is-postgresql">PostgreSQL</a> locally.</p><h4>Why PostgreSQL is Best for You?</h4><p><strong>Key Features:</strong></p><ul><li><strong>User-defined Types</strong>: Customize your own data types.</li><li><strong>Table Inheritance</strong>: Use table inheritance for better data management.</li><li><strong>Sophisticated Locking Mechanism</strong>: Ensures data consistency.</li><li><strong>Foreign Key Referential Integrity</strong>: Maintains database integrity.</li><li><strong>Views, Rules, Subquery</strong>: Powerful query capabilities.</li><li><strong>Nested Transactions (Savepoints)</strong>: Manage transactions more effectively.</li><li><strong>Multi-Version Concurrency Control (MVCC)</strong>: Allows multiple transactions without conflicts.</li><li><strong>Asynchronous Replication</strong>: For high availability.</li><li><strong>Native Microsoft Windows Server Version</strong>: Compatible with Windows servers.</li><li><strong>Tablespaces</strong>: Organize data storage efficiently.</li><li><strong>Point-in-time Recovery</strong>: Restore data to a specific point in time.</li></ul><h4>CRUD Operations in PostgreSQL</h4><p>To add new records to a PostgreSQL table, you first define the table structure.</p><p><strong>Create and Insert Records</strong>: To create a table and insert records</p><pre>CREATE TABLE users ( <br>  id SERIAL PRIMARY KEY, <br>  name VARCHAR (100), <br>  email VARCHAR (100), <br>  age INT <br>); <br><br>INSERT INTO users (name, email, age) VALUES (&#39;John Smith&#39;, &#39;john.smith@example.com&#39;, 32);</pre><p><strong>Read</strong>: To retrieve records</p><pre>SELECT * FROM users; SELECT * FROM users WHERE age &gt; 30;</pre><p><strong>Update</strong>: To update a record</p><pre>UPDATE users SET email = &#39;new.email@example.com&#39; WHERE name = &#39;John Smith&#39;;</pre><p><strong>Delete</strong>: To delete a record</p><pre>DELETE FROM users WHERE name = &#39;John Smith&#39;;</pre><h4>Architecture</h4><p>Its architecture is divided into two primary components: the <strong>client </strong>and the <strong>server</strong>.</p><p>The client sends requests to the server, which processes these requests and sends responses back. Typically, the client and server communicate over a <strong>TCP/IP </strong>network if they are on different hosts.</p><h4>Key Components of PostgreSQL Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ytdLQujvHyJjidna" /></figure><p><strong>1. Shared Memory</strong><br>Shared memory is crucial for efficient data handling and consists of:</p><ul><li><strong>Shared Buffers</strong>: These minimize disk I/O by holding frequently accessed data. The default size has increased from 32MB in older versions to 128MB in versions 9.3 and later.</li><li><strong>WAL Buffers</strong>: Temporarily store changes before they are written to WAL (Write Ahead Log) files, aiding in data recovery.</li><li><strong>Work Memory</strong>: Allocates memory for sorting operations and hash tables during data writes. The default has increased from 1MB to 4MB in newer versions.</li><li><strong>Maintenance Work Memory</strong>: Allocates memory for maintenance tasks like VACUUM and CREATE INDEX, with the default size increasing from 16MB to 64MB.</li></ul><p><strong>2. Background Processes</strong><br>PostgreSQL uses several background processes for various tasks:</p><ul><li><strong>Background Writer</strong>: Regularly performs checkpoint processing.</li><li><strong>WAL Writer</strong>: Periodically writes and flushes WAL data to persistent storage.</li><li><strong>Logging Collector</strong>: Writes log data to files.</li><li><strong>Auto vacuum Launcher</strong>: Manages vacuum operations on tables.</li><li><strong>Archiver</strong>: Copies WAL log files to a specified directory if archive mode is enabled.</li><li><strong>Stats Collector</strong>: Gathers statistics on database activity.</li><li><strong>Checkpointer</strong>: Writes all dirty pages from memory to disk and cleans the buffer area.</li></ul><p><strong>3. Data Files / Data Directory Structure</strong><br>PostgreSQL databases are organized into a cluster, with a specific directory structure:</p><ul><li><strong>pg_version</strong>: Contains database version information.</li><li><strong>Base</strong>: Holds database subdirectories.</li><li><strong>Global</strong>: Contains cluster-wide tables.</li><li><strong>pg_xlog</strong>: Stores WAL files.</li><li><strong>pg_clog, pg_multixact, pg_notify</strong>: Store various status and transaction data.</li><li><strong>pg_stat_tmp</strong>: Holds temporary statistics files.</li></ul><h4>Why is PostgreSQL Unique?</h4><p><strong>Unique Features:</strong></p><ul><li><strong>Pioneered MVCC</strong>: PostgreSQL was the first to implement Multi-Version Concurrency Control (MVCC).</li><li><strong>Custom Functions</strong>: Add custom functions in languages like C/C++, Python, and Java.</li><li><strong>Extensibility</strong>: Define custom data types, index types, and functional languages.</li><li><strong>Custom Plugins</strong>: Enhance and modify the system with custom plugins to meet specific needs.</li></ul><h4>PostgreSQL vs MySQL: A Quick Comparison</h4><p><strong>Similarities:</strong></p><ol><li><strong>Relational Database Management Systems (RDBMS)</strong>: Both organize data into tables.</li><li><strong>SQL Support</strong>: Both use Structured Query Language (SQL) for interacting with the database.</li><li><strong>JSON Support</strong>: Both can store and transport data using JSON (JavaScript Object Notation).</li></ol><p><strong>Differences:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzzEhP6r7b1Q1fOQhaW9Jg.png" /></figure><p><strong>Conclusion:</strong></p><ul><li><strong>PostgreSQL</strong>: Choose PostgreSQL for<strong> enterprise applications</strong> that need robust support for <strong>complex queries, multiple data types, </strong>and<strong> high concurrency.</strong></li><li><strong>MySQL</strong>: Opt for MySQL if you need a fast, easy-to-use database for <strong>small </strong>to <strong>medium-sized</strong> <strong>web applications</strong>.</li></ul><h4>Common Use Cases of PostgreSQL</h4><p><strong>1) Robust Database in the LAPP Stack</strong><br><strong>LAPP </strong>stands for <strong>Linux, Apache, PostgreSQL, </strong>and<strong> PHP (or Python and Perl). </strong>PostgreSQL is often used as a reliable back-end database for dynamic websites and web applications.</p><p><strong>2) General-Purpose Transaction Database</strong><br>Both large corporations and startups use PostgreSQL as their main database to support various applications and products.</p><p><strong>3) Geospatial Database</strong><br>With the <strong>PostGIS</strong> extension, PostgreSQL supports geospatial databases, making it ideal for<strong> geographic information systems (GIS)</strong> for apps like <strong>Uber </strong>and<strong> Citus.</strong></p><h4>Language Support</h4><p>PostgreSQL supports a wide range of popular programming languages, including:</p><ul><li>Python</li><li>Java</li><li>C#</li><li>C/C++</li><li>Ruby</li><li>JavaScript (Node.js)</li><li>Perl</li><li>Go</li><li>Tcl</li></ul><h4>Large Scale users of PostgreSQL</h4><p>Several companies have built products and solutions using PostgreSQL. A few of those companies are<strong> Apple, Fujitsu, Red Hat, Cisco, Juniper Network, etc</strong></p><p>By now, you must have had a clear idea of <strong>PostgreSQL</strong>, from its meaning to working you know all of it now. In a nutshell, <strong>PostgreSQL is a powerful, open-source object-relational database management system known for its advanced features, scalability, and support for complex queries.</strong> So, as you navigate through the vast expanse of the internet, stay informed, stay secure, and embrace the adventure of the digital realm!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b1c26c1405" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-is-postgresql-36b1c26c1405">What is ⁠PostgreSQL?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did Magic Pocket help Dropbox save millions?]]></title>
            <link>https://levelup.gitconnected.com/how-did-magic-pocket-help-dropbox-save-millions-2f744c643194?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f744c643194</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[storage-solutions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 03:06:26 GMT</pubDate>
            <atom:updated>2024-12-06T03:06:26.987Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dropbox scaled its storage with its custom-built system- Magic Pocket, and utilized high-density SMR drives, increasing its gross revenue by 75%.</h4><p><em>You can also check: </em><a href="https://hw.glich.co/p/how-dropbox-scaled-its-storage-infrastructure">How Dropbox scaled its storage infrastructure?</a></p><p>Have you ever wondered how Dropbox is able to synchronize and store countless files for more than 700 million users? In today’s digital age, people keep everything online, ranging from academic documents to business records to family pictures. The architecture of Dropbox is designed to manage substantial quantities of data securely. In the last blog, we discussed the obstacles encountered by Dropbox, let’s explore the strategies implemented by Dropbox in this blog today.</p><p>In case you haven’t gone through PART 1 of <strong>“How Dropbox scaled its storage infrastructure?”</strong>, please go through it in order to understand PART 2 better: <a href="https://hw.glich.co/p/how-dropbox-scaled-its-storage-infrastructure">How Dropbox scaled its storage infrastructure?</a></p><h4>The solution adopted by Dropbox</h4><blockquote>Moving from AWS to Custom Infrastructure ➡️Building Magic Pocket</blockquote><h4>Moving from AWS to Custom Infrastructure</h4><p>As we have read in the last blog also, Dropbox initially relied on <strong>Amazon Web Services (AWS)</strong> for its storage solutions. But as their user base grew, so did their requirements for data, leading to increased expenses in AWS. In order to cut costs and gain better control over their infrastructure, Dropbox made a significant decision in <strong>2016</strong> to <strong>transition from AWS to their own custom-designed data centers.</strong></p><p><strong>Akhil Gupta</strong>, the <strong>Vice President of Infrastructure at Dropbox</strong>, stated that having complete ownership of the entire stack allows them to enhance performance, reliability, and the user experience. By personalizing their systems, they have developed a <strong>competitive advantage </strong>specifically suited to their requirements.</p><h4>Building Magic Pocket</h4><p>The <strong>“Magic Pocket”</strong> started in 2013 with a small team at Dropbox that began to work on this project.</p><p><strong><em>The goal was pretty straightforward: </em></strong><em>To build a file storage system that would end the company’s reliance on AWS. If this project is executed correctly, Dropbox will drastically reduce its monthly AWS bill and also be able to increase its data storage capacity with a personalized touch.</em></p><p>The team at Dropbox already had some experience building and scaling storage systems, since they were managing the metadata of users and files in-house since the company launched in 2007. The team wanted to build a system from the ground up that will be capable of storing <strong>exabytes </strong>of files.</p><p><strong>Do you know?</strong></p><p>One exabyte is the equivalent of a <strong>billion gigabytes</strong>, or <strong>about 245 million DVDs </strong>worth of data.</p><p>The project<strong> Magic Pocket </strong>required the construction of special machines that would be capable of packing in as many hard disk drives as possible. Dropbox hardware engineers custom-built a box measuring <strong>18 inches tall and 44 inches wide,</strong> named <strong>“Diskotech,”</strong> that could store up to a <strong>petabyte’s</strong> worth of data.</p><p>In addition to the hardware challenges, Dropbox software engineers had to create the server architecture and write code that controlled how data was written to the disks themselves. According to the company, 90 percent of its user data had migrated from Amazon’s servers by <strong>October of 2015</strong>, two and a half years after the project began. (Although Dropbox still leverages AWS for its international storage needs.)</p><p><strong>So, this was about the journey of Magic Pocket, but you must be wondering what this Magic Pocket is.</strong></p><p>Engineers at Dropbox explain Magic Pocket as,<strong> “An Exabyte scale blob storage system”.</strong></p><p>Magic Pocket is basically used to store all Dropbox’s customer data. Apart from this, they also have a lot of internal use-cases.</p><p><em>Let’s see some numbers before moving forward:</em></p><ul><li>Magic Pocket is a very large key-value store where the value can be arbitrary-sized blobs.</li><li>Operate across 3 geographical regions in North America.</li><li>99.99% availability &gt; 99.9999999999% of durability</li><li>Their system managed millions of requests per second.</li><li>More than 600000 storage drives are currently deployed</li><li>1000s of computing machines</li></ul><p><strong>Let’s talk about the most important component of Magic Pocket which is the OSD (Object Storage Device)</strong></p><h4>What is OSD (Object Storage Device)?</h4><p>This is a picture of an actual OSD in one of the data centers at Dropbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*FlaaVovL_Ljrlqa-" /></figure><p>An OSD (Object Storage Device) represents a storage unit like a large, specialized hard drive setup, designed to store and manage vast amounts of user data.</p><ul><li>OSDs have about <strong>100 disks per OSD</strong></li><li>They utilize<strong> SMR technology</strong></li><li>Each storage device has over <strong>2 petabytes</strong> of capacity</li></ul><h4>What is SMR Technology and Why they needed this SMR technology?</h4><p>SMR stands for <strong>Shingled Magnetic Recording</strong> and it’s different from the <strong>conventional perpendicular magnetic recording </strong>or<strong> PMI drives</strong> that allow for random writes across the whole disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*jqg38A0642b0j6g_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ndDdBueQMMZDubJl" /></figure><p>With SMR the trade-offs are that you offer increased density by <strong>doing sequential writes instead of random writes </strong>so as you can see in the above figure, you’re squeezing tracks (see the last track) of SMR Drives together which causes the head to erase the next track when you walk over it but in this case, you can still read from it, it’s just that you can’t just randomly write in any place that you want and this was perfect for cases based on the Dropbox’s workload patterns so this ended up working really well for Dropbox.</p><p><strong>In case you had some confusion, let me provide you a better picture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*-AGhnsqXnnVHLJah" /></figure><p>SMR drives also have a <strong>conventional zone </strong>outside the diameter that allows for caching of random writes if you need to, and this conventional zone is typically less than about one percent of the total capacity of the drive.</p><p><strong>Let’s talk about the architecture of magic pocket</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*eVaVUsahiNQV6J7h" /></figure><p>From a very high-level view of Dropbox’s system, it operates out of three zones.</p><p><strong>What do they mean by Pocket?</strong></p><p>Pocket is a way to represent a logical version of everything that makes up the systems at Dropbox so they can have many <strong>different instances of magic pocket</strong> and some versions of that could be a <strong>test pocket, stage pocket, </strong>or <strong>production pocket.</strong></p><p>Also, a thing to note is that the databases and compute are not shared between Pockets, so they operate completely independently of each other.</p><p>Now that we have a high-level view of what a pocket is let’s talk about the different components</p><p><strong>Let’s get into what a zone is!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*uZEwRE4hm0A0uAYO" /></figure><p>Within a zone, they have their first service which is the <strong>Frontend Service</strong> and this is the service that they expose to their clients. So, all of their clients interact with them through this Frontend service.</p><p>This is what they call to make any kind of request and the types of requests the clients typically make are a <strong>PUT </strong>request with the key and a blob, a <strong>GET </strong>request given some key, also they might make a <strong>DELETE </strong>call, they might scan for what hashes are available in the system, they might want to update some metadata on a specific key as well.</p><p>When a GET request is made, the system first consults the hash index, which is a collection of sharded MySQL databases. Each shard is organized by a hash, which serves as a key for a blob. Internally, these blobs are divided into blocks — small pieces of a file, usually no larger than 4 MB. The hash (generated using SHA-256) maps to a specific cell in the index table.</p><p><em>It also has a cell, bucket, and checksum as well for that specific hash.</em></p><p>A cell is another isolation unit where all of the storage devices actually reside. and so the index table just points to the specific cell and a bucket so another level and direction where to go to in the cell the cells can be quite large so they can be over<strong> 100 petabytes in size of customer data </strong>they do have some limitations of how much they can grow but as the system as a whole if they are low on capacity they just simply open up a new cell.</p><p>That’s how their system is able to scale horizontally forever with some limitations of course!</p><p><strong>Let’s talk about what else we have in the zone.</strong></p><p>Another component that we have in the zone is the<strong> cross-zone replicator</strong>. Its job is to replicate data across multiple regions asynchronously in the background. After a commit, your data is queued for replication to other zones, ensuring redundancy and reliability.</p><p>We also have a control plane that handles traffic coordination on its own.</p><p><strong>For example, </strong>during background tasks like migrations or storage machine upgrades (e.g., kernel or OS updates), it creates plans to avoid disrupting live traffic. The control plane also manages cell state, tracking hardware details, and other attributes.</p><p><strong>Let’s get into what a cell and a bucket are!</strong></p><h4>Bucket Service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*pufDTpQtAI2Fw_XR" /></figure><p>Within each cell, data is stored in buckets. To fetch a blob, the process starts with the <strong>bucket service</strong>, which manages buckets and volumes. A bucket maps to a volume, which in turn maps to a set of OSDs (Object Storage Daemons). Volumes can be opened or closed and may use replication or erasure coding for data protection.</p><p>When you request a blob, the bucket points to a specific volume, which identifies the OSD containing the blob. For example, bucket1 might map to volume10, and within that volume, a specific OSD retrieves the blob for you.</p><p>For writers, the process is similar but focuses on open buckets. The frontend service determines which buckets are ready to accept data and writes to the corresponding OSDs within the associated volume. This ensures efficient and organized storage.</p><p><strong>Another very important component is the coordinator</strong></p><p>The <strong>coordinator</strong> operates in the background, not directly involved in PUT or GET requests. Its main job is managing buckets, volumes, and storage machines. It continuously health-checks storage machines, reconciles their data with the bucket service and database, and handles tasks like erasure coding and repairs. For instance, if a storage machine fails, the coordinator ensures data is moved to a healthy machine.</p><p>It also optimizes data placement within a cell and manages storage transitions, like taking a machine offline by relocating its data. However, the coordinator doesn’t move data itself, that’s handled by the <strong>volume manager</strong>, which oversees data transfers, volume recreation, and optimization. Additionally, background verification processes ensure data consistency both within and across cells.</p><p><strong>Let’s talk about a little bit more about buckets and volumes</strong></p><h4>Buckets and volumes?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*OJ28EJGGgMkqQcNJ" /></figure><p>Buckets, volumes, and extents are key components of the storage system.</p><ul><li>A <strong>bucket</strong> is a logical storage unit used for writing data. Each bucket is linked to a <strong>volume</strong>, which is made up of one or more buckets.</li><li>Within a volume, data is stored in <strong>extents</strong>, which are 1–2 GB chunks of data on disk.</li></ul><p>When writing data, the system identifies open buckets, determines their associated OSDs, and writes directly to the extents. The <strong>coordinator</strong> manages the relationships between buckets, volumes, and extents, handling tasks like finding new storage locations if data is lost or ensuring proper placement.</p><p>Volumes also have specific properties, such as being open or closed, replicated or erasure coded. Once a volume is closed, it cannot be reopened. This structure ensures efficient and reliable data storage.</p><p><strong>Now let’s have a high-level overview of their cold storage system</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Nmvuroof7mg0vO7Y" /></figure><p>The inspiration came from <strong>Facebook’s warm blob storage system. </strong>There was a paper that was written a few years ago and had a very interesting idea there.</p><p><strong>The idea is as follows: </strong><em>You have a Blob, and you split it in half, so the first half is blob1 and the second half is blob2 then you take the 3rd part which is going to be the XOR of blob1 and blob2 and we call those fragments. Those fragments will be individually stored in different zones.</em></p><p>Now if you need to get the full blob you simply need any one of these combinations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*4Rmf_hTGxdHg7RV4" /></figure><p>You need to have any of the two regions to be available to do the fetch.</p><p>Let’s talk about some of the wins that they got from the Cold Storage:</p><ul><li>They went from <strong>2x replication to 1.5 replication </strong>and this is a huge amount of savings so this is nearly <strong>25% savings</strong> from a <strong>2X replication</strong> that they had.</li></ul><h4>Financial Impact of Magic Pocket on Dropbox</h4><p>Dropbox’s decision to transition from AWS to its custom-built infrastructure, Magic Pocket, was truly a turning point in its financial performance. By 2016, the company had <strong>migrated over 90% of its user data to Magic Pocket</strong>, achieving substantial cost savings and enhanced operational efficiency. Between <strong>Q1 2016 and Q4 2017</strong>, Dropbox’s gross margins improved from<strong> 46% to 70%</strong>, while its revenue increased from<strong> $185 million to $305.5 million.</strong></p><p>Today, its<strong> gross margins </strong>have <strong>surpassed 75%.</strong></p><h4>Dropbox still uses a “Hybrid Approach”</h4><p>Despite the clear financial benefits of Magic Pocket, Dropbox has not completely abandoned AWS.</p><p><strong><em>For example,</em></strong><em> Dropbox relies on AWS for analytics, desktop client distribution, and international expansion. This flexibility was the key factor in launching S3-backed data centers in Tokyo and Australia which enabled the company to scale globally.</em></p><p>By blending in-house infrastructure with cloud services, Dropbox achieves the best of both worlds. It capitalizes on the cost advantages of Magic Pocket for core storage while utilizing AWS for complementary services where it provides superior technology.</p><p>By now, you must have had a clear idea of <strong>how Magic Pocket helps Dropbox save millions. </strong>In a nutshell, Dropbox efficiently syncs and stores files for over 700 million users by using a custom-built infrastructure, optimized sync protocol, and strategic use of cloud services. Dropbox scaled its storage infrastructure with a custom-built system called Magic Pocket, utilizing high-density SMR drives and advanced data replication for durability and scalability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f744c643194" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-did-magic-pocket-help-dropbox-save-millions-2f744c643194">How did Magic Pocket help Dropbox save millions?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spotify Optimized Their Recommendation System]]></title>
            <link>https://levelup.gitconnected.com/how-spotify-optimized-their-recommendation-system-31f9030051c3?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/31f9030051c3</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 21:01:47 GMT</pubDate>
            <atom:updated>2024-09-19T21:01:47.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>EP 38: How Spotify Optimized Their Recommendation System</h3><h4>Spotify optimized recommendations by combining collaborative filtering, content-based filtering, and audio analysis to deliver highly personalized music recommendations.</h4><p>You can add your response to the poll at the end of the content. We are looking forward to seeing your response.</p><p>Imagine opening your favorite music app and being greeted with a playlist that feels like it was handpicked just for you. Each song seems to match your mood perfectly!</p><p><strong>Ever wondered how Spotify does it for you? </strong>Spotify, one of the leading music streaming platforms, has mastered the art of delivering such personalized music experiences. But how do they do it? Let’s discover in this blog today.</p><h4>What is a Recommendation System?</h4><p>Before diving into Spotify’s methods, let’s briefly understand what a recommendation system is.</p><p><strong>A recommendation system predicts what a user might like based on their past behavior and preferences.</strong></p><p>These systems are used in various applications, from online shopping to video streaming.</p><h4>Spotify’s Challenges</h4><p><em>Spotify faces unique challenges in building its recommendation system because music preferences are highly personal and dynamic. Unlike other content types, music preferences can change based on mood, time of day, and social influences.</em></p><h4>How It All Started:</h4><p>In 2014, Spotify acquired<strong> </strong><a href="https://en.wikipedia.org/wiki/The_Echo_Nest?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-38-how-spotify-optimized-their-recommendation-system&amp;_bhlid=c2c621277312b9f4427b785e3ed69bbc187387bb"><strong>The Echo Nest</strong></a><strong>, </strong>a key move to enhance its recommendation system. The Echo Nest’s advanced machine learning and language processing improved how Spotify analyzed music and user preferences.</p><p>Before this, Spotify used basic collaborative filtering. <strong>The Echo Nest’s technology refined these methods, making recommendations more accurate and personalized.</strong></p><h4>Key Components of Spotify’s Recommendation System</h4><p>Spotify’s recommendation system relies on these main techniques:</p><ol><li><strong>Collaborative Filtering</strong></li><li><strong>Content-Based Filtering</strong></li><li><strong>Audio Analysis</strong></li></ol><h4>Collaborative Filtering</h4><p>Collaborative filtering utilizes user behavior to generate recommendations. If two users have similar music tastes, the system might recommend songs one user has listened to but the other hasn’t.</p><p><em>This process involves matrix manipulation, where user-song play counts are organized into a sparse matrix. The matrix is transformed into two matrices: </em><strong><em>the preference matrix </em></strong><em>and </em><strong><em>the confidence matrix.</em></strong><em> The system then uses an algorithm to find the ‘K’ closest song vectors for every user vector, making recommendations based on these findings.</em></p><p>For example, if you’re a<strong> fan of </strong>Arijit Singh and <strong>enjoy listening to</strong> Shreya Ghoshal, <strong>collaborative filtering notes this pattern</strong>. If another user<strong> loves listening to</strong> Arijit Singh but <strong>hasn’t discovered</strong> Shreya Ghoshal, the system might <strong>recommend </strong>Shreya Ghoshal to them.</p><p>Collaborative filtering can also cluster users with similar music interests, a process known as <strong>user-user collaborative filtering</strong>.</p><p>Another approach is <strong>item-item collaborative filtering</strong>, which focuses on the relationships between items. If many users like the same songs, the system identifies the songs as similar.</p><h4>Limitations of Collaborative Filtering</h4><ul><li>It struggles with the<strong> “cold start”</strong> problem, making accurate recommendations for new users or items without historical data.</li><li>It also suffers from <strong>“popularity bias”</strong>, often recommending popular items while overlooking less-known gems.</li></ul><h4>Content-Based Filtering</h4><p>Content-based filtering helps overcome the cold start problem. It processes songs using a spectrogram to analyze the audio. A <a href="https://saturncloud.io/blog/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way/?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-38-how-spotify-optimized-their-recommendation-system&amp;_bhlid=bb6c095a3fc47cac8497c4f574609b167f1a1ec4"><strong>convolutional neural network (CNN)</strong></a><strong> </strong>understands the song’s characteristics, such as estimated time signature, key, mode, tempo, and loudness. If a new song has similar parameters to a user’s favorite songs, Spotify is likely to recommend it.</p><p><em>Content-based filtering analyzes song attributes to create personalized recommendations. </em><strong><em>It examines metadata, performs raw audio analysis, and considers cultural context</em></strong><em>. For example, it looks at metrics like danceability and loudness, and analyzes lyrics and descriptions.</em></p><p>For instance, if you <strong>frequently </strong>listen to Bollywood songs with <strong>fast-paced beats and a particular vocal style, </strong>content-based filtering will <strong>recommend new songs with similar characteristics.</strong></p><p><em>If you’re a fan of the energetic songs from movies like “Dil Se” or “Kal Ho Naa Ho,” Spotify might recommend other tracks with similar tempo and vocal styles from contemporary Bollywood movies.</em></p><h4>Key Factors Considered:</h4><ul><li><strong>Release Date:</strong> Context about its era.</li><li><strong>Label:</strong> Artist’s style.</li><li><strong>Artist</strong></li><li><strong>Album:</strong> The collection it belongs to.</li><li><strong>Genre:</strong> Musical category.</li><li><strong>Duration:</strong> Length of the track.</li><li><strong>Key Signature:</strong> Tonal center.</li><li><strong>Mode:</strong> Major or minor key.</li><li><strong>Time Signature:</strong> Rhythmic framework.</li><li><strong>Tempo:</strong> Speed of the rhythm.</li><li><strong>Language:</strong> Lyrics language.</li><li><strong>Instruments:</strong> Instruments used.</li><li><strong>Featured Artists:</strong> Additional contributors.</li><li><strong>Producer:</strong> Overseer of production.</li><li><strong>Lyrics:</strong> Words conveying emotions and themes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*pwQ2vGNiJuEQ7C-y" /></figure><h4>Audio<strong> </strong>Analysis</h4><p>Spotify’s audio model enhances recommendations by analyzing raw audio signals, breaking down music into components like<strong> tempo, pitch, and timbre. </strong>This detailed analysis helps understand each track’s unique characteristics.</p><p>For instance, the model can distinguish between the bright sounds of pop and the rich textures of classical music. It also analyzes musical structure, identifying patterns in<strong> melody, harmony, dynamics, style, and instrumentation. </strong>This ensures recommendations align closely with users’ preferences.</p><h4>Regional Relevance</h4><p>Music reflects the values, traditions, and experiences of its creators and listeners. Every song has a unique imprint of the culture and region from which it originates.</p><p>To provide a more personalized experience, Spotify uses<strong> </strong><a href="https://www.reddit.com/r/explainlikeimfive/comments/axnk0o/eli5_what_is_natural_language_processing/?utm_source=hw.glich.co&amp;utm_medium=referral&amp;utm_campaign=ep-38-how-spotify-optimized-their-recommendation-system&amp;_bhlid=9c624167a0b18244b64f9092fb7ce4fac0d09edd"><strong>natural language processing (NLP)</strong></a><strong> </strong>to analyze news articles, blogs, and online reviews. This helps compile a list of the most frequently used descriptors for a particular song or artist, which are then used to find commonalities between artists, songs, and user preferences.</p><p>For example, Indian music often incorporates regional elements like <strong>traditional instruments (e.g., sitar, tabla), linguistic diversity, </strong>and <strong>cultural themes. </strong>By analyzing these elements, Spotify can offer recommendations that resonate with your regional and cultural preferences.</p><p><em>If you enjoy the soulful ghazals of Jagjit Singh or the classical renditions by Pandit Ravi Shankar, Spotify will consider these preferences when suggesting new music.</em></p><h4>Limitations of Using AI</h4><ul><li>AI-driven music recommendation systems heavily rely on user data to curate personalized playlists. While this enhances user experience, it can also lead to an <strong>echo chamber effect</strong>, where the system only recommends music similar to what the user has already listened to, limiting exposure to new genres and artists.</li><li>Discovering new and diverse music is a complex task for AI. The <strong>algorithm must balance recommending songs within a user’s comfort zone and introducing them to unfamiliar genres or artists. </strong>Too much of the latter can alienate the user.</li></ul><p>❝</p><p><strong>Spotify’s suggestions aren’t always Accurate</strong></p><p>Despite the sophisticated AI and ML techniques, Spotify’s suggestions are not always perfect. Any Spotify user like me, you or any of us knows that even with AI piecing together their musical identity, the system can still throw out a recommendation that misses the mark.</p><p>By now, you must have had a clear idea of <strong>How Spotify Optimized Their Recommendation System.</strong> In a nutshell<strong>, </strong>Spotify optimized their recommendation system by combining<strong> collaborative filtering, content-based filtering, </strong>and <strong>advanced audio analysis</strong> to deliver highly personalized music recommendations.</p><p><strong>Congratulations! You’ve just advanced another step in your tech journey. Keep progressing!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31f9030051c3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-spotify-optimized-their-recommendation-system-31f9030051c3">How Spotify Optimized Their Recommendation System</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is an ORM?]]></title>
            <link>https://levelup.gitconnected.com/what-is-an-orm-dba2cb967a14?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba2cb967a14</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 14:45:56 GMT</pubDate>
            <atom:updated>2024-03-22T14:45:56.475Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever found yourself juggling between the numerous lines of code and the complexities of managing data in a database? Imagine you’re building a new application, and you need a place to store your data.</p><p>Now you enter the world of databases to figure out the best one as per your needs. But here’s the twist: <strong>databases speak their own language (SQL), and your code communicates in another (probably JavaScript, Python, or Java). This language barrier is where ORM (Object Relational Mapping) comes to the rescue!</strong></p><p><strong>Think of ORM as your multilingual friend who effortlessly translates your instructions between you (the code) and the database.</strong> No more lost-in-translation moments — thanks to ORM! Come on let’s dive deeper into the world of ORM in this blog today.</p><p>Let’s say you have this object with you:</p><p><strong>STUDENT OBJECT</strong></p><pre>{<br>  rollNo: 12 <br>  name: &quot;Rohit&quot;<br>  sub: &quot;Python&quot;<br>}</pre><p>Now, imagine a scenario where storing this object is as seamless as a magical process. Behind the scenes, all the required database operations happen automatically. No need for you to write the SQL queries — YES this is possible!</p><p>This is where ORM steps in!</p><h3>What is an ORM?</h3><p>ORM which stands for Object Relational Mapping, is a technique we use to connect to databases using their syntax rather than queries.</p><p>It is a concept that is present in various programming languages like Java, Python, or .NET. Regardless of the language you’re working with, the question arises — should you use ORM, and what’s the rationale behind adopting this concept? But before delving into when to use it, let’s talk about what is ORM.</p><p><strong>Consider this scenario:</strong></p><p>In any Object-Oriented Programming language or a language supporting Object-Oriented Concepts, the most important thing is the object. An object encapsulates data through variables and executes actions through methods.</p><p>To explain in simple terms, an object knows something, an object does something. Now when you say an <strong>object knows something</strong>, it does that with the help of <strong>variables</strong> and when you say the <strong>object does something</strong>, it does that with the help of <strong>methods</strong>.</p><p><strong>Why do we use variables?</strong></p><p>Essentially, variables serve the purpose of storing data. The entire software industry revolves around managing information — storing it, retrieving it, and processing it.</p><p>Imagine storing data in a variable; essentially, you are utilizing an object to encapsulate and manage that data. However, what if you desire more longevity for your data? What if you wish to make that data persist over time? Here’s where the concept of databases comes into play.</p><p>Whether it’s a relational database like Oracle, MySQL, or PostgreSQL, the goal is to store data in a manner that ensures its permanence — we call this persistent storage.</p><h3>How do you store the data residing in an object in a database?</h3><p>As some understand some specific language, databases have their own language. One way to store data is through SQL.</p><p>SQL stands for Structured Query Language and is a computer language that we use to interact with a relational database. It is mainly used for organizing, managing, and retrieving data from a computer database.</p><p>When dealing with Database Management Systems (DBMS), particularly Relational Database Management Systems (RDBMS), SQL is the language of choice.</p><p>With SQL, you can perform a variety of operations, including data retrieval, storage, updating, and altering table structures. You can do everything with the SQL language and it’s a very powerful language.</p><p>That means if you want to be a software developer you need to focus on a language let’s say Java or C# and in the backend, you have to also learn how to work with databases with the help of SQL.</p><h4>But what if we can just move this part?</h4><p>Consider SQL — typically, when storing object details in a database, you begin by extracting all the values from the object variables.</p><p>For instance, if you have a student object with properties like student ID (rollNo), name, and subject, you collect these values. All this thing is available in the object format- in the variables format. Subsequently, to store this information in a database, you employ a SQL query.</p><pre>INSERT into student values (12, ‘Rohit’, ‘Python’);</pre><p>Every interaction with the database involves SQL queries. Whether you’re inserting data into a table, fetching information using a select query, or updating records with an update query, SQL is at the core of these operations. This means that as a developer, you need to have a good understanding of SQL.</p><h4>But what if I say you don’t have to learn SQL?</h4><p>Imagine you’re working in any programming language, and you have an object. Instead of manually writing SQL queries to save that object’s data into a database, you say, “Hey, I want to save this object.”</p><p>Now, behind the scenes, magic happens.</p><p>The system automatically understands that you’re storing this object, and it seamlessly <strong>translates and stores the data in the database</strong>, eliminating the need for you to write explicit SQL queries as a programmer.</p><p>But behind the scenes, someone will have to do it right?</p><p>Your DBMS only works with SQL queries so you can’t say there’s no SQL. There is SQL but you as a programmer not directly writing it. However, you have tools/libraries that assist you in managing this process, ensuring you don’t have to manually write the SQL queries.</p><p><strong>These techniques are called ORM techniques which stands for Object Relational Mapping.</strong></p><p>You incorporate this technique in between your framework any programming language, and your database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*f0oYFVVHdd9pJHJ-" /></figure><p>Basically, you are actually talking to ORM and this will store the data in the database. <strong>Who is responsible for making the SQL queries? This ORM</strong>! You don’t have to do anything.</p><p>But is it really possible? Can we just save the data in the database just by using the object? The answer is YES! Consider how you create an object in Java.</p><p>In Java, you require a class to create an object.<strong> This class serves as your design blueprint, and the object is an instance of that blueprint</strong>. You can have multiple objects for one class.</p><p>Let’s say if you talk about students, you will create only one student class and you will have multiple objects.</p><pre>class Student { <br>    int rollNo;<br>    String name;<br>    String sub; <br>}</pre><p>Imagine you have a classroom with 20 students. For each student, you will have a distinct object. Each of these objects will have a unique roll number, a different name, and possibly a different or common subject of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/0*qbTx88SC3z4Pbqvv" /></figure><p>When considering creating tables in a database, think of it as having a box with multiple columns and rows.</p><p>At the beginning of the application, you don’t have any data; you just have the column structure. You might have a “roll number” column, a “name” column, and a favorite “subject” column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hy3IJFqNEDGbucZWmpil9Q.png" /></figure><p>Can we say that this class and this table are related? The class name corresponds to your table name, and the class variables (or the variables you have mentioned) become your columns. What about the objects? Every time you get a new object, it will have different data. Can we say each object becomes one row? So, if you have 20 objects, you’ve got 20 rows here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ceitOUl5hG_uPZ992gfRA.png" /></figure><p>We are basically trying to relate object-oriented concepts with database concepts, and that is what is called Object-Relational Mapping. Okay, so you don’t have to do anything as a programmer.</p><p>When we talk about Java we have <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2hpYmVybmF0ZS5vcmcvP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtNC13aGF0LWlzLWFuLW9ybSIsInBvc3RfaWQiOiI3ZWVkNjBlNS1kZjQ0LTRkNjctODE1OC1lNmE1NGMyOWYxY2IiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiMzU3ZjkyZmMtMjYzYy00YzYzLWIwNjctNjkwZjljYTJmNDcwIiwiaWF0IjoxNzEwOTM1ODUwLCJpc3MiOiJvcmNoaWQifQ.IN4c6q_giCfDyJmJys6hNscDf_64DIuvHI0RBbXT9O8"><strong>HIBERNATE</strong></a>, if you talk about Django which uses Python, which has nm ORM built in, if you talk about GoLang it also has <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2dvcm0uaW8vaW5kZXguaHRtbD91dG1fc291cmNlPWh3LmdsaWNoLmNvJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWVwLTQtd2hhdC1pcy1hbi1vcm0iLCJwb3N0X2lkIjoiN2VlZDYwZTUtZGY0NC00ZDY3LTgxNTgtZTZhNTRjMjlmMWNiIiwicHVibGljYXRpb25faWQiOiI4NzE1NTY4YS1hZjY4LTQ3MTgtYWRmYy0wMTZkYmZmZDJiMDkiLCJ2aXNpdF90b2tlbiI6IjM1N2Y5MmZjLTI2M2MtNGM2My1iMDY3LTY5MGY5Y2EyZjQ3MCIsImlhdCI6MTcxMDkzNTg1MCwiaXNzIjoib3JjaGlkIn0.OAivleEPnPk5nZDXFkFJ0nyhns6PmH_urdHdX9apYnI"><strong>GORM</strong></a><strong>,</strong> if you talk about .NET also has <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2xlYXJuLm1pY3Jvc29mdC5jb20vZW4tdXMvZWYvP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtNC13aGF0LWlzLWFuLW9ybSIsInBvc3RfaWQiOiI3ZWVkNjBlNS1kZjQ0LTRkNjctODE1OC1lNmE1NGMyOWYxY2IiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiMzU3ZjkyZmMtMjYzYy00YzYzLWIwNjctNjkwZjljYTJmNDcwIiwiaWF0IjoxNzEwOTM1ODUwLCJpc3MiOiJvcmNoaWQifQ.RuCKrwwcNX98XtiQGRpLnGhLIcEJh952kHAjruukMtk"><strong>Entity framework</strong></a>, if you use Nodejs, or any Javascript runtime you have a lot of options like <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL29ybS5kcml6emxlLnRlYW0vP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtNC13aGF0LWlzLWFuLW9ybSIsInBvc3RfaWQiOiI3ZWVkNjBlNS1kZjQ0LTRkNjctODE1OC1lNmE1NGMyOWYxY2IiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiMzU3ZjkyZmMtMjYzYy00YzYzLWIwNjctNjkwZjljYTJmNDcwIiwiaWF0IjoxNzEwOTM1ODUwLCJpc3MiOiJvcmNoaWQifQ.l19NHyPvO-XWoJq2PjDo9w-_Mov6SA0RtAsS6H2FyFE"><strong>Drizzle</strong></a>, <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5wcmlzbWEuaW8vP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtNC13aGF0LWlzLWFuLW9ybSIsInBvc3RfaWQiOiI3ZWVkNjBlNS1kZjQ0LTRkNjctODE1OC1lNmE1NGMyOWYxY2IiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiMzU3ZjkyZmMtMjYzYy00YzYzLWIwNjctNjkwZjljYTJmNDcwIiwiaWF0IjoxNzEwOTM1ODUwLCJpc3MiOiJvcmNoaWQifQ.l2KrlDkYjRWgmU5OUFmsjMRH5xMvkaZNMj5ULF0WkRM"><strong>Prisma</strong></a>, and <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3NlcXVlbGl6ZS5vcmcvP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtNC13aGF0LWlzLWFuLW9ybSIsInBvc3RfaWQiOiI3ZWVkNjBlNS1kZjQ0LTRkNjctODE1OC1lNmE1NGMyOWYxY2IiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiMzU3ZjkyZmMtMjYzYy00YzYzLWIwNjctNjkwZjljYTJmNDcwIiwiaWF0IjoxNzEwOTM1ODUwLCJpc3MiOiJvcmNoaWQifQ.m_iFsp_vQmbY-HIVgmJqunuonQAi2EZ6GmYstTgAA4k"><strong>Sequlize</strong></a>.</p><p>Mainly you use this technique in between and you say hey technique this is my object, save that in a database then we’ll say okay it’s done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*RYIW12RxAD2c1W7X" /></figure><p>That’s how they do it. So they write all the queries for you. Behind the scenes, if you check, they actually create a select query. So if you say, “Hey ORM, I have this roll number and can you give me the data for it?” basically, we use some, let’s say, GET methods. In this case, it will fire a SELECT query. When you say save, it will fire an INSERT query. When you say the data is already there, it will fire the UPDATE query. And what if you say you want to delete it? It will fire the DELETE query. So everything will be done by your ORM technique.</p><p>Let’s picture this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Et330YgoMGIWcMwz" /></figure><p>Basically, this is happening behind the scenes,</p><p>The term “Relational” in ORM refers to the Relational Table in the Database. The database can be SQL, MySQL, PostgreSQL, etc. The term “Object” refers to the Object of a class. And finally the term “Mapping” refers to the mapping between these two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*UTWtCos-b2TOHOqT" /></figure><p>It basically maps the fields from the Student class to the columns of the Student Table.</p><p>For example: The ID from the student class is directly mapped with the ID column from the student table. So we can directly create objects of the student class and store them in a student database table. Basically, we don’t have to write SQL statements to insert the record into the student’s table. We can use ORM to directly map objects to the relational database table.</p><p>To summarize,</p><p><strong><em>ORM is a programming technique that maps application domain model objects to relational database tables.</em></strong></p><p><strong>Pros of Using ORM:</strong></p><ul><li>One of the significant advantages is the time saved for programmers.</li><li>ORM techniques handle query generation, reducing manual SQL coding.</li><li>You write less code when using ORM techniques than with SQL.</li><li>It decreases the cost of development.</li><li>ORM techniques are built to eliminate the possibility of SQL injection attacks.</li></ul><p><strong>Cons of Using ORM:</strong></p><ol><li><strong>Complexity Limitations:</strong> As projects become more complex, some ORM techniques may lack features for executing complex tasks. Customized queries might be necessary.</li><li><strong>Performance Debate:</strong> There’s an ongoing debate about the impact on application speed. ORM might slow down the application slightly, especially when compared to manually optimized SQL queries. However, the difference might just be a fraction of a second. But when we talk about scale those seconds matter a lot.</li><li><strong>Debatable Speed:</strong> While ORM aids faster development, there’s a debate on whether it slows down runtime performance. In performance tests, the difference is often minimal but may be noticeable in milliseconds.</li></ol><p><strong>Considerations:</strong></p><ol><li><strong>Customized Queries:</strong> ORM allows for customized queries. In Java, for instance, JPA supports JPQL or HQL, resembling SQL but adapted for object-oriented structures.</li><li><strong>Developer Experience:</strong> If you’re experienced in writing optimized SQL queries, using ORM might seem less efficient. ORM techniques have their query-building methods, which may not align perfectly with manual optimization.</li></ol><p>Despite the debates, the consensus is positive. ORM remains a valuable technique, accelerating product development, and reducing the likelihood of bugs. While it might have limitations and trade-offs, the time saved and development advantages make it a worthwhile choice for many projects.</p><p>By now, you must have had a clear idea of <strong>ORM.</strong> However, understanding ORM on a theoretical level is just the first step. To know the practical aspects of working with ORM, you can try working with it by using it in some of your projects.</p><p>Anyway, Congratulations! You’re already one step ahead in the journey of ORM. <strong>Keep going!</strong></p><blockquote><strong>The post was originally published at </strong><a href="https://hw.glich.co/p/what-is-an-orm"><strong>What is an ORM?</strong></a><strong> which is a part of my newsletter called </strong><a href="https://hw.glich.co/subscribe?utm_source=medium&amp;utm_medium=bottom&amp;utm_campaign=what-is-an-orm"><strong>Hello, World!</strong></a><strong> where we help developers learn a new software engineering concept every Monday. Read what engineers from Google, Microsoft, and Amazon are reading for free.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dba2cb967a14" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-is-an-orm-dba2cb967a14">What is an ORM?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is reverse proxy and proxy?]]></title>
            <link>https://blog.devgenius.io/what-is-reverse-proxy-and-proxy-4d1c70beb540?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d1c70beb540</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 17:41:59 GMT</pubDate>
            <atom:updated>2024-03-04T17:41:59.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how your digital identity remains cloaked when you traverse the web? Thought about how websites recognize you when you log in without repeatedly asking for your password?</p><p>Or maybe you’ve heard about “proxies” and “reverse proxies” but aren’t sure what they do? Don’t worry; we’re here to simplify it all for you. Let’s dive deeper into the world of proxy and reverse proxy today.</p><p>Before moving forward, let’s see the literal meaning of Proxy.</p><p>A Proxy is someone or something that has the authority to function (do something) on behalf of another person or thing. Thus, Proxy generally means acting on behalf of others.</p><p>In terms of computers and networks, a Proxy is a server!</p><h3>What is a Proxy Server?</h3><p>A Proxy Server generally known as a “Forward Proxy Server” acts as a middleman that sits between a private network and the public internet.</p><p>Basically, <strong>a Proxy Server acts on behalf of clients on a network</strong>, such as retrieving data for those clients.</p><p>Let’s picture this with the help of a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*3JDd6BVg1Gk6G5Z8" /></figure><p>Each of these computers has access to the Internet. But as most of us know, with all these computers having the ability to access the internet, it could also create a potential security risk as they could draw in malicious traffic posing a significant threat to the network.</p><p>And this is where a Proxy Server steps in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UWLEDt5A-fZD5HkK" /></figure><p>When a Forward Proxy Server is used on this network, the Proxy Server is now the guardian of this network. So now, instead of individual computers directly accessing the internet, they route their requests through the Proxy Server.</p><p>The Proxy Server then retrieves the data from the internet on their behalf, establishing a protective barrier between the private network and the internet.</p><h3>Benefits of Proxy Server:</h3><ul><li><strong>It can regulate traffic by blocking harmful websites.</strong></li><li><strong>It hides the identities of the client by masking their IP addresses and using its own IP address.</strong></li><li>When the clients connect to websites and servers out on the internet, those websites and servers only see the IP address of the Proxy Server and not the client.</li><li><strong>It logs user activity.</strong></li><li>Many organizations prefer to monitor the websites their clients visit. Utilizing a proxy allows them to track the visited websites and the duration of their clients’ presence on those sites.</li><li><strong>It can bypass restricted content.</strong></li><li>Certain institutions such as schools and governments may impose restrictions on accessing specific websites. However, employing a proxy might provide a way to bypass these restrictions and gain access to those restricted websites.</li><li><strong>It increases speed by caching (storing) copies of websites in its database.</strong></li><li>A Proxy Server can store copies of frequently visited websites, eliminating the need to fetch the same content repeatedly from the internet all over again. These websites are stored in the proxy’s cache database for quicker access.</li></ul><h3>Examples of Forward Proxy Server:</h3><ul><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5waHAtcHJveHkuY29tLz91dG1fc291cmNlPWh3LmdsaWNoLmNvJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWVwLTMtd2hhdC1pcy1yZXZlcnNlLXByb3h5LWFuZC1wcm94eSIsInBvc3RfaWQiOiI1MmJkMDJiMS1iYjg3LTRkOTgtYmRjNi03MmZlMDhmY2JkYzAiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiNmQ5MTdkMGEtMDhlNC00MjY1LWJhMjItZDljNmRlNTMwMDJkIiwiaWF0IjoxNzA5NDg5NzMyLCJpc3MiOiJvcmNoaWQifQ.SImSE9G36MUP1qtx4HV3wgxySytYJ2_BmsxS2XCKQw4"><strong>PHP-Proxy</strong></a></li><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwOi8vd3d3LnNxdWlkLWNhY2hlLm9yZy8_dXRtX3NvdXJjZT1ody5nbGljaC5jbyZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1lcC0zLXdoYXQtaXMtcmV2ZXJzZS1wcm94eS1hbmQtcHJveHkiLCJwb3N0X2lkIjoiNTJiZDAyYjEtYmI4Ny00ZDk4LWJkYzYtNzJmZTA4ZmNiZGMwIiwicHVibGljYXRpb25faWQiOiI4NzE1NTY4YS1hZjY4LTQ3MTgtYWRmYy0wMTZkYmZmZDJiMDkiLCJ2aXNpdF90b2tlbiI6IjZkOTE3ZDBhLTA4ZTQtNDI2NS1iYTIyLWQ5YzZkZTUzMDAyZCIsImlhdCI6MTcwOTQ4OTczMiwiaXNzIjoib3JjaGlkIn0.OxKYtMd3pDGNZAVLipZn5JQG_HJthNIvu3bBcqB6K_A"><strong>Squid</strong></a></li><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5qbWFyc2hhbGwuY29tL3Rvb2xzL2NnaXByb3h5Lz91dG1fc291cmNlPWh3LmdsaWNoLmNvJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWVwLTMtd2hhdC1pcy1yZXZlcnNlLXByb3h5LWFuZC1wcm94eSIsInBvc3RfaWQiOiI1MmJkMDJiMS1iYjg3LTRkOTgtYmRjNi03MmZlMDhmY2JkYzAiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiNmQ5MTdkMGEtMDhlNC00MjY1LWJhMjItZDljNmRlNTMwMDJkIiwiaWF0IjoxNzA5NDg5NzMyLCJpc3MiOiJvcmNoaWQifQ.iufipvwobMvs3_dmSUru7TFPHBF3Nng3P6A0cpZ-WBU"><strong>CGI-Proxy</strong></a></li></ul><p>By now, you must have got an idea of the proxy server. Now let’s move forward to the reverse proxy server.</p><h3>What is Reverse Proxy?</h3><p>Just like the name says, it is the reverse of the forward proxy server. Positioned on a network, <strong>the reverse proxy doesn’t control outgoing traffic but instead manages incoming traffic to the network.</strong></p><p>Let’s picture this with the help of a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*FZPhygaQNNWVWn3s" /></figure><p>Imagine a situation where a user is requesting dashboard data and it goes to server A and when accessing profile data, the request goes to server B. These servers accept connections from clients on the Internet.</p><p>However, <strong>direct access to servers poses security risks, making them vulnerable to potential problems caused by hackers.</strong> The problem of unequal load on a server also increases if the same server receives an ample amount of requests. This is where a reverse proxy can help!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*7EYp1WzC9jMbJFaN" /></figure><p>Introducing a reverse proxy to this network establishes <strong>a centralized entry point that manages incoming traffic.</strong> When computers from the internet seek access to data on these servers, they no longer connect directly to the servers.</p><p>Instead, they communicate with the reverse proxy server, which retrieves the data from the server and forwards it back to the computer.</p><h3>Benefits of Reverse Proxy Server:</h3><ul><li><strong>It increases the security by hiding the IP addresses of the servers.</strong></li><li>How does it achieve this? It does so by hiding the IP addresses of the servers.</li><li>So when a computer on the internet wants to access a website on one of these servers, it won’t see the IP address of the server; instead, it will only see the IP address of the reverse proxy.</li><li><strong>It blocks malicious traffic such as DDOS (Distributed denial of Service) attacks.</strong></li><li>What happens in a DDOS attack? A DDOS attack is a simultaneous attack from a bunch of computers over the internet targeting a specific server by its IP address.</li><li>A reverse proxy is an effective defense against this type of attack because it will position itself between the client and the server, serving as a buffer to prevent the attack from reaching the server and it will also hide the server’s IP address.</li><li><strong>Load Balancing</strong></li><li>In a network, multiple servers often manage incoming traffic, and there can be instances where certain servers face more traffic than others, leading to overload.</li><li>To address this issue, a reverse proxy functions as a traffic cop, distributing traffic evenly among multiple servers to prevent overloading on specific servers.</li></ul><h3>Examples of Reverse Proxy Server:</h3><ul><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5uZ2lueC5jb20vP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtMy13aGF0LWlzLXJldmVyc2UtcHJveHktYW5kLXByb3h5IiwicG9zdF9pZCI6IjUyYmQwMmIxLWJiODctNGQ5OC1iZGM2LTcyZmUwOGZjYmRjMCIsInB1YmxpY2F0aW9uX2lkIjoiODcxNTU2OGEtYWY2OC00NzE4LWFkZmMtMDE2ZGJmZmQyYjA5IiwidmlzaXRfdG9rZW4iOiI2ZDkxN2QwYS0wOGU0LTQyNjUtYmEyMi1kOWM2ZGU1MzAwMmQiLCJpYXQiOjE3MDk0ODk3MzIsImlzcyI6Im9yY2hpZCJ9.Sv4yzgBUTAX7pQxI1cFL6zRQhGjBwS0zAtkvB9L4Hxc"><strong>NGINX</strong></a></li><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5oYXByb3h5LmNvbS8_dXRtX3NvdXJjZT1ody5nbGljaC5jbyZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1lcC0zLXdoYXQtaXMtcmV2ZXJzZS1wcm94eS1hbmQtcHJveHkiLCJwb3N0X2lkIjoiNTJiZDAyYjEtYmI4Ny00ZDk4LWJkYzYtNzJmZTA4ZmNiZGMwIiwicHVibGljYXRpb25faWQiOiI4NzE1NTY4YS1hZjY4LTQ3MTgtYWRmYy0wMTZkYmZmZDJiMDkiLCJ2aXNpdF90b2tlbiI6IjZkOTE3ZDBhLTA4ZTQtNDI2NS1iYTIyLWQ5YzZkZTUzMDAyZCIsImlhdCI6MTcwOTQ4OTczMiwiaXNzIjoib3JjaGlkIn0.O5dht5FaGi_rKQ4-gKrn4NSGqtEt0e4XFfxpcnsYHKc"><strong>HAProxy</strong></a></li><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2xpbmtlcmQuaW8vP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtMy13aGF0LWlzLXJldmVyc2UtcHJveHktYW5kLXByb3h5IiwicG9zdF9pZCI6IjUyYmQwMmIxLWJiODctNGQ5OC1iZGM2LTcyZmUwOGZjYmRjMCIsInB1YmxpY2F0aW9uX2lkIjoiODcxNTU2OGEtYWY2OC00NzE4LWFkZmMtMDE2ZGJmZmQyYjA5IiwidmlzaXRfdG9rZW4iOiI2ZDkxN2QwYS0wOGU0LTQyNjUtYmEyMi1kOWM2ZGU1MzAwMmQiLCJpYXQiOjE3MDk0ODk3MzIsImlzcyI6Im9yY2hpZCJ9.Zl27srOZAioKt_9WQ_IFFtAb5fIlkNUNzIY5MAEIqw4"><strong>Linkerd</strong></a></li><li><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2lzdGlvLmlvLz91dG1fc291cmNlPWh3LmdsaWNoLmNvJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWVwLTMtd2hhdC1pcy1yZXZlcnNlLXByb3h5LWFuZC1wcm94eSIsInBvc3RfaWQiOiI1MmJkMDJiMS1iYjg3LTRkOTgtYmRjNi03MmZlMDhmY2JkYzAiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiNmQ5MTdkMGEtMDhlNC00MjY1LWJhMjItZDljNmRlNTMwMDJkIiwiaWF0IjoxNzA5NDg5NzMyLCJpc3MiOiJvcmNoaWQifQ.Jcm9UhcnTvTjj2cooN6sYbKHxM3F5AttpY30T8xyVKY"><strong>Istio</strong></a></li></ul><h3>Similarities between Forward and Reverse Proxy Servers:</h3><ul><li>They <strong>provide protection</strong> to devices within a private network from potential threats originating from the internet and external networks.</li><li><strong>Both are capable of restricting the types and sizes of files passing through them</strong>, preventing unauthenticated users from sending requests.</li><li><strong>Port and protocol switching</strong> are functionalities present in both forward and reverse proxies.</li><li><strong>At times, the same software can be used for configuring both forward and reverse proxies</strong>. For instance, widely used software like Nginx and the Apache web server can be set up to function as both reverse and forward proxies in enterprise architectures.</li></ul><h3>Differences between Forward and Reverse Proxy Servers:</h3><p><strong>Forward Proxy Server</strong></p><ol><li>Responsible for handling outgoing requests.</li><li>Represents clients to the Internet.</li><li>It provides client anonymity.</li><li>It enhances client privacy and content control.</li><li>It can be a part of the client-side infrastructure.</li><li>It has the potential for misuse and performance impact.</li><li>Examples: <strong>PHP-Proxy, Squid, CGI-Proxy, etc.</strong></li></ol><p><strong>Reverse Proxy Server</strong></p><ol><li>Responsible for handling incoming requests.</li><li>Represents server to the Client.</li><li>It provides server anonymity.</li><li>It functions as a load balancer and protects the server.</li><li>It’s part of the server-side infrastructure.</li><li>It adds complexity and can become the single point of failure.</li><li>Examples: <strong>NGINX, HAProxy, Linkerd, Istio, etc.</strong></li></ol><blockquote><strong>A forward proxy is there to protect clients, while a reverse proxy is there to protect servers.</strong></blockquote><p>By now, you must have had a clear idea of <strong>Reverse Proxy and Proxy</strong>, from their basic literal meaning to the benefits you know all of now. However, understanding Proxy Servers on a theoretical level is just the first step.</p><p>The next step is to gain practical knowledge by working/building/using the proxy servers.</p><p>Anyway, Congratulations! You’re already one step ahead in the journey of Proxy Servers. <strong>Keep forging ahead!</strong></p><blockquote>The post was originally published at <a href="https://hw.glich.co/p/what-is-reverse-proxy-and-forward-proxy">What is reverse proxy and proxy?</a> which is a part of my newsletter called <a href="https://hw.glich.co/subscribe?utm_source=medium&amp;utm_medium=bottom&amp;utm_campaign=what-is-reverse-proxy-and-proxy">Hello, World!</a> where we help developers learn a new software engineering concept every Monday. Read what engineers from Google, Microsoft, and Amazon are reading for free.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d1c70beb540" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-is-reverse-proxy-and-proxy-4d1c70beb540">What is reverse proxy and proxy?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the Hell Are JWT tokens?]]></title>
            <link>https://javascript.plainenglish.io/what-the-hell-are-jwt-tokens-709af910f291?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/709af910f291</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 10:17:39 GMT</pubDate>
            <atom:updated>2024-03-04T10:17:39.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>What the Hell Are JWT Tokens?</h3><p>Have you ever logged into a website or app and wondered how it knows you’re you, without asking for your password every time? Or perhaps you’ve heard the term “JWT tokens” thrown around in tech discussions and thought, “What the heck is JWT tokens?” Don’t worry, we’re here to make things simple for you. Let’s dive deeper into the world of JWT tokens in this blog…</p><p>For quite a while, web cookies were the go-to for user authentication. They still do the job well in certain scenarios, but sometimes, we need more flexibility. That’s where JSON Web Token (JWT) comes into play. As a newer and more open standard, it’s becoming increasingly popular among major websites and apps. Stick around to uncover what JWT really is.</p><p>But wait!!</p><p>Before moving forward, <strong>Let’s understand the traditional cookie working better with a detailed diagrammatic explanation:</strong></p><p>As we mentioned at the start of the blog, earlier cookies were used when JWT was not there in the picture. Let’s take an example of a traditional login system that uses sessions and cookies to store the user data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*jqOfx6CGGfyvlxsa.png" /></figure><p><strong>Step 1:</strong> The user logs in from the client by posting any form of login. It could be email-password, user id-password etc.</p><p><strong>Step 2:</strong> As soon as this information reaches the server, the server is going to do the authentication to make sure that the user is correct. If everything is correct, then the user information will be stored in the session which will be stored in the memory of the server, and they will get a unique ID called session ID.</p><p><strong>Step 3:</strong> The session ID is sent back to the browser using a cookie.</p><p><strong>Step 4:</strong> The browser will always have the session ID with itself and whenever a new request is made, the session ID is sent back to the server. Suppose the client wants to go to a new page in the application then that session ID gets sent along with the cookie to the server.</p><p><strong>Step 5:</strong> The server will go into the session memory, and it will check if it has something in memory that corresponds to this particular ID. If so then it means the user will have access to the information.</p><p><strong>Step 6:</strong> If the user authorization is successful, the response is sent back to the browser.</p><h3>Issues with this approach</h3><p>There were some issues associated with this approach</p><ul><li>The server needs to store the sessions and in case of server restart the session may be lost and all the users will have to log in again.</li><li>Even if we use a different service for handling sessions there will still be a dependency on that service being resilient all the time as authentication is an important part of a system.</li><li>The server needs memory to handle this data, which can increase if there are a lot of users using the service.</li></ul><p>So what other options do we have? Enters JWT token.</p><h3>What is a JWT Token?</h3><p>JWT stands for “JSON Web Token”.</p><p>Imagine you’re at a party, and the host gives you a unique wristband with a secret pattern. This wristband serves as your entry ticket and gives you access to all the goodies — the food, drinks, and fun activities at the party. You don’t have to keep telling the host who you are; your wristband speaks for you. This is somewhat like what JWT tokens do in the digital world.</p><p>JWT, or JSON Web Token, is like a secure digital envelope. It wraps up important information and puts a trustworthy seal on it, ensuring that whoever sends it is exactly who they claim to be.</p><p>Before moving further, let’s first Decode the Key Components of JWT Tokens:</p><ul><li><strong>JSON:</strong> Short for JavaScript Object Notation, JSON is a text-based data transmission format in web applications. It stores information in an easy-to-access manner, both for developers and computers thus making its use widespread.</li><li><strong>Tokens:</strong> In simple terms, a token is a data string symbolizing something else, like an identity. In authentication, a non-JWT token is a character string enabling the receiver to verify the sender’s identity.</li><li><strong>JWT Structure:</strong> A compact, self-contained standard for transmitting information.</li></ul><h3>Use Cases of JWTs</h3><ol><li><strong>Authentication:</strong> After a user successfully logs in with their credentials, they receive an ID token. This token, following <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL29wZW5pZC5uZXQvc3BlY3Mvb3BlbmlkLWNvbm5lY3QtY29yZS0xXzAuaHRtbD91dG1fc291cmNlPWh3LmdsaWNoLmNvJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWVwLTItd2hhdC10aGUtaGVsbC1pcy1qd3QtdG9rZW5zI0lEVG9rZW4iLCJwb3N0X2lkIjoiMmNiNzk2NWEtZTEzMS00YWNlLWI5ZmMtODc0M2U1OTE2MjBlIiwicHVibGljYXRpb25faWQiOiI4NzE1NTY4YS1hZjY4LTQ3MTgtYWRmYy0wMTZkYmZmZDJiMDkiLCJ2aXNpdF90b2tlbiI6ImI4Zjk2MzJkLTU4NmEtNGQxNy1hZDdiLTE0YTMxOGYxMWIxMCIsImlhdCI6MTcwOTM3MTE3OSwiaXNzIjoib3JjaGlkIn0.jJDQIsFNOe99z19NIlxrT6Uly_dUL8O9wFkmUh0K-CA"><strong>OpenID Connect (OIDC)</strong></a> specifications, always takes the form of a JWT.</li><li><strong>Authorization:</strong> Once a user logs in, an application may seek access to routes, services, or resources on the user’s behalf. To achieve this, an Access Token is required in every request, often taking the form of a JWT.</li><li><strong>Information Exchange:</strong> JWTs provide a secure method for exchanging information between parties. The fact that they can be signed assures that you can trust that the senders are indeed who they claim to be. The structured format of JWTs also allows easy verification, ensuring the content remains untampered.</li></ol><h3>How does JWTs work?</h3><p>While dealing with APIs, the most challenging task is to validate the users. By validating the users, we mean that verifying the users are who they claim to be. This is generally referred to as Authentication.</p><p>When sending a request to the server, the client includes an API key where the key contains the information related to the user which identifies the user.</p><p>But the major concern during this whole process of authentication is, how the server will be going to validate the issued key.</p><blockquote>➡️ This is where JWTs come in!</blockquote><blockquote>Each JWT token is composed of Header, Payload, and Signature.</blockquote><blockquote><strong>Header</strong>- Contains metadata about the token itself.</blockquote><blockquote><strong>Payload</strong>- Contains arbitrary data relevant to the system.</blockquote><blockquote><strong>Signature</strong>- Used to verify the authenticity of the token.</blockquote><p>JWTs work by using a secret key (“secret”) to sign each token. It is then the task of the server to validate the token by recomputing the present digital signature using its private secret key(“secret”).</p><p>During this whole process if any tampering happens then the whole verification process will fail thus concluding that the user is not the one who they claim to be.</p><p><strong>Let’s check authentication using JWT tokens in a client-server environment:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*imnvng1USXe1SAi8.png" /></figure><p><strong>Step 1:</strong> A post request is made to the server with an email and password.</p><p><strong>Step 2:</strong> Instead of storing the information on the server inside the session memory, the server creates a JWT token encodes and serializes that, and signs it with its own secret key so the server knows that if you tamper with it then it’s invalid.</p><blockquote>The main difference here is: <strong>Nothing is stored on the server.</strong> The JWT will have all the information about the user-built into it. <strong>You should not store any sensitive information inside the JWT token as it is viewable by anyone.</strong></blockquote><p><strong>Step 3:</strong> The server sends back the JWT token to the browser.</p><blockquote>The browser can choose to store the received JWT however it wants. Example: You can do cookie storage.</blockquote><p><strong>Step 4:</strong> When the client sends the request again to the server, it will include the JWT token so that it knows which user is authenticating.</p><p><strong>Step 5:</strong> The server verifies the JWT token if it has changed or not from the time it has been signed. If everything is correct then it deserializes the JWT token and verifies if the user is authorized to use that resource then it will send the response back to the client.</p><h3>Issues it solves:</h3><p>Some of the issues that we had with session-based authentication can be solved by using JWT.</p><ul><li>The server does not need to store the JWT token but they just create it and send it back to the client, hence distributed. The server only needs to put compute in verifying it rather than storing it as in the case of session-based authentication.</li><li>Even if the server is down, no one needs to log in again since the server only has the secret key it uses to decode the JWT token.</li></ul><h3>JWT Format</h3><p>Each JWT token is composed of a Header, Payload, and Signature.</p><ul><li><strong>Header</strong></li></ul><ol><li>The header contains the data about the token itself. It is mainly used to give information about the signing/decryption technique used on it.</li><li>It can also hold key information about the media or content type of the transmitted data. All this information is present as a JSON object then this JSON object is encoded to <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5iYXNlNjRlbmNvZGUub3JnLz91dG1fc291cmNlPWh3LmdsaWNoLmNvJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWVwLTItd2hhdC10aGUtaGVsbC1pcy1qd3QtdG9rZW5zIiwicG9zdF9pZCI6IjJjYjc5NjVhLWUxMzEtNGFjZS1iOWZjLTg3NDNlNTkxNjIwZSIsInB1YmxpY2F0aW9uX2lkIjoiODcxNTU2OGEtYWY2OC00NzE4LWFkZmMtMDE2ZGJmZmQyYjA5IiwidmlzaXRfdG9rZW4iOiJiOGY5NjMyZC01ODZhLTRkMTctYWQ3Yi0xNGEzMThmMTFiMTAiLCJpYXQiOjE3MDkzNzExNzksImlzcyI6Im9yY2hpZCJ9.2qJdCqjHApgovPfUoE1fuURli206LRb1NBd2-wUxdJI"><strong>BASE64URL</strong></a>.</li></ol><ul><li><strong>Payload</strong></li></ul><ol><li>It can contain any data related to your system. Basically, it can have the data you want to feed in i.e. it may include the user’s ID with a list of features they can interact with.</li><li>The information is presented as key/value pairs and the keys are called “claims” in JWT. Even this is encoded to BASE64URL.</li></ol><ul><li><strong>Signature</strong></li></ul><ol><li>A signature is used to verify the authenticity of the token. It ensures that the token hasn’t been altered along its way.</li><li>The signature of a JSON Web Token is created using the BASE64URL encoded header and payload which are joined together with dot(.) which is further hashed using the hashing algorithm mentioned in the header with a secret key.</li><li>This signature is then appended to the header and payload using dot(.) which forms our actual token header.payload.signature</li></ol><blockquote>These 3 components join together to form the JWT.</blockquote><blockquote>📎 [header].[payload].[signature]</blockquote><p>In order to have a better view of JWTs and their working, let’s check this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*DdIG2-IR2WVUc9l9.png" /></figure><p>Creating a JSON Web Token (JWT) involves encoding a header and payload into Base64URL format, generating a signature using the indicated algorithm (HMAC-SHA256 in this case), and combining these parts to form the final JWT.</p><p>This process ensures the integrity and authenticity of the token. Fortunately, most programming languages offer libraries that automate the JWT generation, eliminating the need for manual implementation.</p><p>💡 Remember, the <strong>payload that you send in the JWT is public and anyone can view it</strong>. JWT just helps us verify whether a user is valid or not and not be used as a source of sensitive data storage.</p><p><a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwOi8vSldULklPP3V0bV9zb3VyY2U9aHcuZ2xpY2guY28mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249ZXAtMi13aGF0LXRoZS1oZWxsLWlzLWp3dC10b2tlbnMiLCJwb3N0X2lkIjoiMmNiNzk2NWEtZTEzMS00YWNlLWI5ZmMtODc0M2U1OTE2MjBlIiwicHVibGljYXRpb25faWQiOiI4NzE1NTY4YS1hZjY4LTQ3MTgtYWRmYy0wMTZkYmZmZDJiMDkiLCJ2aXNpdF90b2tlbiI6ImI4Zjk2MzJkLTU4NmEtNGQxNy1hZDdiLTE0YTMxOGYxMWIxMCIsImlhdCI6MTcwOTM3MTE3OSwiaXNzIjoib3JjaGlkIn0.XCM9jdVknCetjIYlTcnOsM92T52hvBmwVKjwlNpyBYM"><strong>JWT.IO</strong></a><strong> allows you to decode, verify, and generate JWT:</strong> <a href="https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2p3dC5pby8_dXRtX3NvdXJjZT1ody5nbGljaC5jbyZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1lcC0yLXdoYXQtdGhlLWhlbGwtaXMtand0LXRva2VucyIsInBvc3RfaWQiOiIyY2I3OTY1YS1lMTMxLTRhY2UtYjlmYy04NzQzZTU5MTYyMGUiLCJwdWJsaWNhdGlvbl9pZCI6Ijg3MTU1NjhhLWFmNjgtNDcxOC1hZGZjLTAxNmRiZmZkMmIwOSIsInZpc2l0X3Rva2VuIjoiYjhmOTYzMmQtNTg2YS00ZDE3LWFkN2ItMTRhMzE4ZjExYjEwIiwiaWF0IjoxNzA5MzcxMTc5LCJpc3MiOiJvcmNoaWQifQ.xwsoG2GpdhdrdK5Jzuhac373sNq0uHHrK8NkUbnGTAo"><strong>JSON Web Tokens — jwt.io</strong></a></p><p>You just need to write the payload and secret and can choose the algorithm further which will generate the JWT token for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*HNphxMe7e4WV_Hi8.png" /></figure><p>Let’s see how a token turns out to be in the end after all this:</p><ul><li><strong>Header</strong>: It contains the algorithm you will be using to encode and decode.</li></ul><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ul><li><strong>Payload</strong>: It contains all the information you store in the token.</li></ul><pre>{<br>  &quot;sub&quot;: &quot;Rohit&quot;,<br>  &quot;name&quot;: &quot;Hello, World!&quot;,<br>  &quot;iat&quot;: 124111102023<br>}</pre><ul><li><strong>Verify Signature</strong>: It allows us to verify that the token hasn’t been changed by the client before it gets sent back to us.</li></ul><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; +<br>  base64UrlEncode(payload),<br>  your-256-bit-secret<br>)</pre><p>Tick on “secret base64 encoded” if your secret is base64 encoded otherwise leave it blank. It will generate the JWT token accordingly.</p><p>The Token will look like:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJSb2hpdCIsIm5hbWUiOiJIZWxsbywgV29ybGQhIiwiaWF0IjoxMjQxMTExMDIwMjN9.jBWWWvyUnkguSSXtphPqkSbmGieh3nq2QiqrDJJDlwc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*5GRdEpLa3ncSyimc.png" /></figure><p>Now if we try to tamper our data, let’s remove a few alphabets from the data.</p><p>It suddenly starts showing, “<strong>Invalid Signature</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*VwJpW4LN1PynQNx0.png" /></figure><p>It happened so because what happens behind the scenes is that when the server gets the information from the client, they decode the header and the payload by base64urlencoding and then hash it using the mentioned algorithm and then it is going to check if it matches the last portion of the key.</p><p>If it does matches with the last portion of the key then we got to know that the user didn’t mess with anything in between. But if we get the different last portion after hashing then we know that the key has been tampered with.</p><p>By now, you must have had a clear idea of <strong>JWTs</strong>, from its format to use cases to working you know all of it now. However, understanding JWTs on a theoretical level is just the first step.</p><p>To know the practical aspects of working with JWTs, consider working with JWTs in your upcoming projects. Anyway, Congratulations! You’re already one step ahead in the journey of JWTs. <strong>Keep forging ahead!</strong></p><blockquote>The post was originally published at <a href="https://hw.glich.co/p/what-is-jwt-token">What the hell is JWT tokens?</a> which is a part of my newsletter called <a href="https://hw.glich.co/subscribe?utm_source=medium&amp;utm_medium=bottom&amp;utm_campaign=what-the-hell-is-jwt-tokens">Hello, World!</a> where we help developers learn a new software engineering concept every Monday. Read what engineers from Google, Microsoft, and Amazon are reading for free.</blockquote><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709af910f291" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/what-the-hell-are-jwt-tokens-709af910f291">What the Hell Are JWT tokens?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is an API?]]></title>
            <link>https://levelup.gitconnected.com/what-is-an-api-e62bb48c44ca?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e62bb48c44ca</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 13:04:44 GMT</pubDate>
            <atom:updated>2026-09-16T14:18:51.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how different apps and services present in your phone seamlessly communicate with each other, allowing you to book an Uber through Google Maps or share your latest tweet on Facebook? All thanks to something called an <strong>API</strong>, which stands for <strong>Application Programming Interface</strong>. Let’s dive deeper into the world of APIs in this blog today.</p><h3>What’s an API?</h3><p>In simple terms, API is just an output to an input that you gave to someone. They’re like the ordering system for your software. You give them instructions (inputs), and they reliably provide you with what you asked for (predictable outputs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VJLo2Pnm2ImkffAt" /></figure><p>Let’s consider the most widely used Google Maps, when we give the address as an input, it gives you back that address’s latitude/longitude coordinates as an output.</p><p>Let’s understand APIs better with a real-life analogy.</p><p><strong>Analogy: The Remote Control</strong></p><p>Think of an API as a remote control for your home entertainment system. When you want to change the channel on your TV, increase the volume, or play a DVD, you don’t need to understand the complex electronics inside your devices. You simply press buttons on the remote control, and your commands are executed.</p><p>In this analogy:</p><ul><li>The remote control serves as a client, providing a user-friendly interface.</li><li>The various entertainment devices (TV, sound system, DVD player), this is where the logic is i.e. server.</li><li>Your commands (changing channels, adjusting volume) represent API requests.</li></ul><p>Just as the remote control abstracts the technical complexities of your entertainment system, APIs abstract the inner workings of software systems, allowing them to communicate and perform tasks with ease.</p><h3>The Power of APIs</h3><p>APIs are the backbone of modern software development. They allow developers to leverage existing services and functionalities, saving time and resources. From the data you receive from a weather app to the seamless integration of social media platforms, APIs are everywhere to enhance our daily digital experiences.</p><p>In brief:</p><ul><li>APIs make cross-platform development a breeze.</li><li>APIs are like standardized contracts for communication.</li><li>APIs facilitate communication between services.</li><li>APIs also play a crucial role in security.</li></ul><p><strong>Payment Gateway APIs:</strong> When you make an online purchase, the payment process is often facilitated by payment gateway APIs like PayPal, Stripe, or Square. They handle secure transactions, sparing developers from implementing complex payment systems.</p><p><strong>Social Media Sharing APIs:</strong> Social media platforms offer APIs that allow users to share content from other apps directly to their social feeds. For instance, the “Share on Facebook” option in various apps is made possible through Facebook’s API.</p><h3>How does an API Work?</h3><p>APIs function through a request and response process, sharing data among applications, systems, and devices. When a user interacts with an application, they initiate a request for data, which is sent to the API. The API retrieves the data and returns it to the user, completing the cycle.</p><p>To illustrate this process, let’s liken APIs to the workings of a restaurant. In this analogy, the user plays the role of a customer placing an order. The API functions as the restaurant’s order-taking service, receiving the order details, specifying the desired items, and arranging the preparation process. The kitchen staff, akin to an API server, ensures that the order is accurately prepared and ready for delivery. Any additional requests, such as specifying cooking preferences or adding extra toppings, are handled seamlessly. This comparison serves to simplify the concept of APIs by drawing parallels with a familiar scenario — the ordering process in a restaurant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*6Er9AqaDTjE1SgIK" /></figure><p>For example, imagine a user interacting with a restaurant API to place an order for a pizza. The user specifies the type of pizza, size, toppings, and any special instructions through the API (<strong>Input</strong>). The API, acting as the order handler, communicates this information to the restaurant’s system (<strong>Server</strong>). The Chef then prepares the pizza according to the specifications. Once ready, the pizza is delivered to the user’s location (<strong>Response</strong>), ensuring a smooth and efficient process facilitated by the restaurant API.</p><p>Take a closer look, the API client assembles requests based on user actions and sends them to the relevant API endpoint. These endpoints are like URLs, providing access to specific resources in a database.</p><p>For instance, if a user wants to view products in an e-commerce store, the API client sends a GET request to the /products endpoint. This way, APIs enable efficient data exchange in the digital world.</p><h3>How API works between client and server</h3><p>Imagine a client-server architecture where the client, representing the user, makes requests through a middleman — the API — and receives responses from the server in the backend. Here’s how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*C-Sondrd9qgYKwEH" /></figure><ol><li>Your client kicks things off by initiating the API requests via the URI (<strong>Uniform Resource Identifier</strong>)</li><li>The API request is sent to the server, relaying your intentions.</li><li>The server processes your request, gathers the necessary information, and sends back a response.</li><li>The API, acting as the go-between or the communication channel, hands you the response containing the data you need.</li></ol><p>APIs are designed to be secure, using authorization credentials and an API gateway to control access and keep things safe. For extra layers of security, various techniques like HTTP headers, query string parameters, and cookies are employed.</p><h3>Types of APIs</h3><p>APIs are categorized into many different types based on the use case. In practical experience, I’ve come across people using the term “API” in three different contexts. These are:</p><p><strong>Based on Accessibility:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*qDS-A_S-t1JgAkbj" /></figure><p><strong>Private APIs:</strong> These are also known as internal APIs. When companies create their applications, they build them using a set of interacting APIs. They’re used within an organization to connect various software components. Private APIs are not available for third-party use.</p><p>For example, an e-commerce platform might have numerous private APIs for order processing, product catalog, recommendation, payment processing, etc. working altogether coordinating with each other.</p><blockquote>💭 <strong>Even database calls are API calls under the hood.</strong> The queries that we do are sent to the database through an API call. The database then proceeds to run that query and return the data as a response.</blockquote><p><strong>Public APIs:</strong> Public APIs provide access to an organization’s data or services for third-party developers. These APIs can be freely available or offered as paid products. Sometimes, companies make some of their APIs available to the public and provide instructions on how to use them.</p><p>A good example is the YouTube Data API, YouTube provides a public API that allows developers to access and interact with YouTube’s vast video content, including searching for videos, retrieving video details, uploading videos, and managing user playlists.</p><p>Developers can use this API to create applications that integrate YouTube video features, such as video search, recommendations, and video uploading, into their own platforms. This public API has enabled the development of various third-party YouTube applications and services.</p><p><strong>Code Interfaces:</strong> Now, the first two types of APIs are quite practical, but developers also use the term “API” for lower-level stuff in code, like functions.</p><p>A code interface API, or simply a code API, refers to a set of functions, methods, or procedures that a programming language or library provides for developers to interact with and use in their code.</p><p>A classic example is the Math.random() function in JavaScript. It&#39;s an API that generates random numbers. There are other mathematical operations like Math.power() (power), Math.round() (round), and Math.sqrt() (Square root).</p><blockquote>💡 There might be different types of API, but one thing is in common, they give an output based on an input. They might be named Public, Private, or Code Interfaces but still use API as a single term to describe them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*NSy0xrksllbzRvrY" /></figure><p><strong>Based on Architectural Style:</strong></p><p>Some of the most used types of APIs are:</p><ol><li><strong>REST:</strong> Representational State Transfer (REST) is the most common architectural style for Internet data transfer. It uses standard HTTP methods like GET, POST, PUT, and DELETE to interact with resources through endpoints.</li><li><strong>SOAP:</strong> Simple Object Access Protocol (SOAP) uses XML to exchange structured messages between a client and server. It’s often used in enterprise environments and offers advanced security features but can be slower than other architectures.</li></ol><h3>How developer talks about APIs</h3><blockquote>“I’ve developed an API that allows you to discover the top 10 trending videos on YouTube tailored to your preferences, delivering personalized content effortlessly.”</blockquote><p>Less manual work and faster access to the desired search result.</p><blockquote>“I keep encountering this authentication issue with the API; it’s like trying to enter a password that I can’t quite get right.”</blockquote><p>The API is throwing this puzzling auth error at me, like a locked door that requires the right key. I’m struggling to get through with the correct credentials.</p><blockquote>“You can use the Facebook API to get that data into your app”</blockquote><p>Connect your app with the Facebook API, and you can pull in data seamlessly. It’s like having a magic portal to grab the information you need for your application.</p><blockquote>“I crafted an API that acts like a personal shopper, finding you the best book recommendations based on your preferences. It’s your literary guide in the vast bookstore of information.”</blockquote><p>The future is here! Getting things done within moments in a few touches.</p><p>By now, you must have had a clear idea of <strong>APIs,</strong> from its working to testing you know all of it now. However, understanding APIs on a theoretical level is just the first step. To know the practical aspects of working with APIs, you can try working on them by implementing some of the concepts in projects.</p><blockquote>The post was originally published at <a href="https://scaleengineer.com/blog/what-is-an-api">What is an API?</a> which is a part of my newsletter called <a href="https://scaleengineer.com/subscribe?utm_source=medium&amp;utm_medium=bottom&amp;utm_campaign=what-is-an-api">Hello, World!</a> where we help developers learn a new software engineering concept every Monday. Read what engineers from Google, Microsoft, and Amazon are reading for free.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e62bb48c44ca" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-is-an-api-e62bb48c44ca">What is an API?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Node.js, EJS with TypeScript using Gulp and Webpack]]></title>
            <link>https://javascript.plainenglish.io/setup-node-js-ejs-with-typescript-using-gulp-and-webpack-135aeb93165?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/135aeb93165</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Sat, 31 Jul 2021 14:59:37 GMT</pubDate>
            <atom:updated>2021-08-30T14:27:15.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*F_XcAyjFvgTTfJIv.png" /></figure><p>This post assumes that you want to use TypeScript for the backend as well as frontend (using EJS template) in Node.js, but are struggling to set up <strong>a system to transpile the TypeScript code to JavaScript for the backend as well as frontend which a browser can understand.</strong></p><p>The source code is available on GitHub <a href="https://github.com/RohitLakh/node-ejs-with-typescript-starter-project">here</a>.</p><h3>Basic setup</h3><p>To continue with the post you need to have node and npm installed in your system</p><p>Let’s create a node project</p><h3>Setting up Node.js with TypeScript</h3><p>In order to work with TypeScript in Node.js, we need to install some dev dependency that would help us to run TypeScript with nodemon.</p><pre>npm i -D typescript ts-node @types/node</pre><p>the @types install the type alias for the package.</p><p>Now let’s install nodemon</p><pre>npm i -g nodemon</pre><p>Let’s install express</p><pre>npm i express</pre><p>We would also need the types alias for express. So let’s install that too</p><pre>npm i -D @types/express</pre><p>Now let’s initiate a tsconfig.json</p><p>Now, installing the basic dependencies is done, let’s define the directory structure.</p><pre>├── node_modules/<br>├── dist/<br>├── src/<br>│   ├── config/<br>│   │   └── debug.ts<br>│   ├── public/<br>│   │   ├── assets<br>│   │   └── ts/<br>│   └── views/<br>├── app.ts<br>├── package-lock.json<br>├── package.json<br>└── tsconfig.json</pre><p>Whatever code that we would write would be in the src directory and the build would be in the dist directory.</p><p>The TypeScript for the frontend would be in the ts folder which is inside the public folder.</p><p>All the ejs template file would go into the views directory.</p><h3>Configure your tsconfig.json</h3><p>Since we would be using TypeScript for node, we need to make some changes in the tsconfig.json file.</p><p>This would be enough to get us working. If you would like to know more options in tsconfig, check out <a href="https://www.typescriptlang.org/tsconfig">tsconfig documentation</a></p><p>So the final tsconfig.json would look like this</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;noImplicitAny&quot;: true,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true<br>  }<br>}</pre><p>Now let’s write the code for getting the server up and running.</p><pre>import express, { Application } from &quot;express&quot;;<br>import http from &quot;http&quot;;<br>import debug from &quot;./config/debug&quot;;<br><br>const app: Application = express();<br>const server: http.Server = http.createServer(app);<br><br>// Setting the port<br>const port = debug.PORT;<br><br>// Starting the server<br>server.listen(port, () =&gt; {<br>    console.log(`SERVER RUNNING ON ${port}`);<br>});</pre><p>Now run the server</p><pre>nodemon src/app.ts</pre><p>You should see</p><pre>SERVER RUNNING ON 3000</pre><p>This is all good, nodemon is handling everything, but now if you notice there is no dist directory being generated. Let&#39;s use gulp to generate the dist directory and nodemon to watch for changes. Both would help us automate the entire process</p><p>Let’s install gulp, gulp-typescript, and del</p><pre>npm i -D gulp gulp-typescript del</pre><p>Now on the root directory of the project create a gulpfile.js file</p><p>gulpfile.js</p><pre>var gulp = require(&quot;gulp&quot;);<br>var ts = require(&quot;gulp-typescript&quot;);<br>var tsProject = ts.createProject(&quot;tsconfig.json&quot;);<br>var del = require(&quot;del&quot;);<br><br><br>// Task which would transpile typescript to javascript<br>gulp.task(&quot;typescript&quot;, function () {<br>    return tsProject.src().pipe(tsProject()).js.pipe(gulp.dest(&quot;dist&quot;));<br>});<br><br>// Task which would delete the old dist directory if present<br>gulp.task(&quot;build-clean&quot;, function () {<br>    return del([&quot;./dist&quot;]);<br>});<br><br>// Task which would just create a copy of the current views directory in dist directory<br>gulp.task(&quot;views&quot;, function () {<br>    return gulp.src(&quot;./src/views/**/*.ejs&quot;).pipe(gulp.dest(&quot;./dist/views&quot;));<br>});<br><br>// Task which would just create a copy of the current static assets directory in dist directory<br>gulp.task(&quot;assets&quot;, function () {<br>    return gulp.src(&quot;./src/public/assets/**/*&quot;).pipe(gulp.dest(&quot;./dist/public/assets&quot;));<br>});<br><br>// The default task which runs at start of the gulpfile.js<br>gulp.task(&quot;default&quot;, gulp.series(&quot;build-clean&quot;,&quot;typescript&quot;, &quot;views&quot;, &quot;assets&quot;), () =&gt; {<br>    console.log(&quot;Done&quot;);<br>});</pre><p>Now run the file by</p><p>After the default task finishes check your directory, you would see a dist directory generated. It should have the config, public/ts, public/asset, views directory with app.js</p><p>Now run the server using</p><pre>node dist/app.js</pre><p>You should see</p><pre>SERVER RUNNING ON 3000</pre><p>To automate the server which listens to file changes and builds and re-runs the server again, we need to install another package.</p><pre>npm i -D npm-run-all</pre><p>Now we need to create some scripts in order for the server to watch for changes and re-run the server again with the new changes.</p><p>In your package.json add this code inside your scripts object</p><pre>{<br>    &quot;start:gulp&quot;: &quot;npm-run-all gulp start&quot;,<br>    &quot;gulp&quot;: &quot;gulp&quot;,<br>    &quot;start&quot;: &quot;node ./dist/app.js&quot;,<br>    &quot;dev&quot;: &quot;nodemon --watch src -e ts,ejs --exec npm run start:gulp&quot;<br>}</pre><p>Basically what this does is check for changes and if found then re-runs the gulp command which transpile the TypeScript code and then runs the server using start.</p><p>You should again see</p><pre>SERVER RUNNING ON 3000</pre><p><strong>So now we have TypeScript running with Node.js using Gulp.</strong></p><h3>Setting up EJS templates</h3><p>To work with EJS templates in Node.js, we need to install some npm packages. Let’s install them</p><pre>npm i express-ejs-layouts ejs</pre><p>Now after installing we need express to know that we want to use EJS as the view engine and add the root path for the views so express knows where they are.</p><p>Add these in app.ts</p><pre>import expressLayouts from &#39;express-ejs-layouts&#39;;<br><br>// EJS setup<br>app.use(expressLayouts);<br><br>// Setting the root path for views directory<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));<br><br>// Setting the view engine<br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);</pre><p>Now let’s add some EJS templates into the mix</p><p>Create a new file under views and name it layout.ejs</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;title&gt;Node Typescript&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div&gt;&lt;%- body %&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now save it and add another file and name it index.ejs in the same directory as layout.ejs</p><pre>&lt;h1&gt;Hello world&lt;/h1&gt;<br><br>&lt;!-- This is the script that we would be creating later --&gt;<br>&lt;script src=&quot;./js/scripts.js&quot;&gt;&lt;/script&gt;</pre><p>And save the index.ejs file. Now, since the templates are ready we would need a route where we can render this page. So let&#39;s create that</p><p>In your app.ts file add</p><pre>import { Request, Response } from &quot;express&quot;;<br><br>/* Home route */<br>app.get(&quot;/&quot;, (req: Request, res: Response) =&gt; {<br>	res.render(&quot;index&quot;)<br>});</pre><p>And now run the server and go to http//:localhost:3000. You should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*tHS5lzjytTnPWt1C.png" /></figure><p>Now we have out ejs views setup it&#39;s time to add write some scripts to ejs templates.</p><h3>Serving static content in express</h3><p>Before adding some scripts we need to let express know where our static content is so it can serve it. Add this in the app.ts file.</p><pre>const publicDirectoryPath = path.join(__dirname, &quot;./public&quot;);<br>app.use(express.static(publicDirectoryPath));</pre><p>So now we have a public directory set up now let’s move ahead with using TypeScript with EJS.</p><p>Let’s create 3 files inside public/ts directory and let&#39;s name them as scripts.ts, student.ts, professor.ts</p><p>professor.ts</p><pre>export default class Professor {<br>    name: string;<br>    constructor(name: string){<br>        this.name = name<br>    }<br>}</pre><p>student.ts</p><pre>import Professor from &quot;./professor&quot;;<br><br>export default class Student {<br>  name: string;<br>  favProfessor: Professor;<br>  constructor(name: string, professor: Professor) {<br>    this.name = name;<br>    this.favProfessor = professor;<br>  }<br><br>  getFavProfessor = () =&gt; {<br>     return this.favProfessor<br>  }<br><br>}</pre><p>script.ts</p><pre>import Professor from &quot;./professor&quot;;<br>import Student from &quot;./student&quot;;<br><br><br>const professor: Professor = new Professor(&quot;James Mathew&quot;)<br><br>const student: Student = new Student(&quot;Rohit Lakhotia&quot;, professor)<br><br>console.log(student.getFavProfessor())</pre><p>So here, the file professor.ts contains the professor class and the student.ts file contains the student class with a method getFavProfessor which gets the student&#39;s favorite professor.</p><p>And the scripts.ts file imports both those files and output the student&#39;s favorite professor basically trying to import and export class/function which would happen in a real-world project.</p><p>Now since the script.ts file is the starting point we need to import that in the EJS template that we created before.</p><blockquote><strong><em>Browsers don’t understand TypeScript. </em></strong><em>S</em><strong><em>o we would need to transpile the TypeScript into JavaScript so that the browser can understand it.</em></strong></blockquote><p>Run the server using</p><pre>npm run dev</pre><p>Now if you see the dist/ts directory, and check out scripts.js file, you can see the converted JavaScript file. Now let&#39;s try running it.</p><p>But before that, we would need to make some changes. In index.ejs, just change the scripts.js location to take the script from ts directory. So it would like this.</p><pre>&lt;script src=&quot;./ts/scripts.js&quot;&gt;&lt;/script&gt;</pre><p>Now run the server using</p><pre>npm run dev</pre><p>The server should start now and then now go to http://localhost:3000 and open the console in the browser and if you see <strong>exports is not defined</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ifOJ4gTUIXpUMw4u.png" /></figure><p>Just add this before the script tag in index.ejs</p><pre>&lt;script&gt;var exports = {}&lt;/script&gt;</pre><p>Now try running it. It would show a new error and that will be ‘<strong>require is not defined’.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pGmr9yyUpyonzAln.png" /></figure><p>This is because if you see <strong>the transpile JavaScript file you would see the </strong><strong>require function is there and the browser can&#39;t understand that</strong></p><p>This is because when <strong>transpiling the code, it was transpiled according to Node which can work with require function.</strong></p><p>So now what?</p><p>You can find the source code up to this point here in the master branch on this <a href="https://github.com/RohitLakh/node-ejs-with-typescript-starter-project">repository</a></p><h3>Webpack to the rescue</h3><p>So webpack is a JavaScript bundler, basically, it converts your asset into single/multiple bundles so you can ship the bundle to the end-user basically reducing the number of HTTP calls made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwJXjNoRXpvOdyyd0dMXwA.png" /></figure><p>We would be two methods for this to work</p><ol><li><strong>Bundling the JavaScript generated into a single bundle</strong></li><li><strong>Bundling the TypeScript directly into a bundle</strong></li></ol><p>Both the process would give the same output, but they would differ in the build times.</p><p>But before that, we need to install webpack and webpack-cli</p><pre>npm i -D webpack webpack-cli</pre><p>After this create a new webpack.config.js file in the root directory</p><h3>Bundling the JavaScript generated into a single bundle</h3><p>So here we will be generating the bundle from the already created files inside the dist/public/ts folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*H7BGIWivaVKXlFgimRME5Q.png" /></figure><p>In the webpack.config.js file add this code</p><pre>// The base directory that we want to use<br>const baseDirectory = &quot;dist&quot;;<br><br>module.exports = {<br>  // The current mode, defaults to production<br>  mode: &quot;development&quot;,<br><br>  // The entry points (&quot;location to store&quot;: &quot;location to find&quot;)<br>  entry: {<br>    &quot;public/js/scripts&quot;: [`./${baseDirectory}/public/ts/scripts`],<br>    // &quot;other output points&quot; : [&quot;other entry point&quot;] <br>  },<br><br>  // Used for generating source maps (used for debugging)<br>  devtool: &quot;eval-source-map&quot;,<br><br>  // The location where bundle are stored<br>  output: {<br>    filename: &quot;[name].js&quot;,<br>  },<br>};</pre><p>Save the file and now we need to run the webpack command in order to bundle the JavaScript into a bundle, but this should be automated.</p><p>So now in package.json file, add a new script</p><pre>&quot;webpack&quot;: &quot;webpack&quot;</pre><p>And we need to run this after the gulp script is done running, so after the gulp command, we need to add webpack. So the final scripts object would look like:</p><pre>{<br>    &quot;start:gulp&quot;: &quot;npm-run-all gulp webpack start&quot;,<br>    &quot;webpack&quot;: &quot;webpack&quot;,<br>    &quot;gulp&quot;: &quot;gulp&quot;,<br>    &quot;start&quot;: &quot;node ./dist/app.js&quot;,<br>    &quot;dev&quot;: &quot;nodemon --watch src -e ts,ejs --exec npm run start:gulp&quot;<br>}</pre><p>Now before running npm run dev, just go to the index.ejs inside the src/views directory and make the scripts is loading from the js directory.</p><p>And then run</p><pre>npm run dev</pre><p>Now after the server is running successfully go to the http://localhost:3000 and check the console, you should see the Professor object consoled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rrFpBlYN3tFsk-TW.png" /></figure><p><strong>Congrats it’s working now. Basically, you were able to use TypeScript in the browser using webpack.</strong></p><h4>Advantages:</h4><ul><li>Faster build time as compared to transpiling the frontend TypeScript directly to JavaScript using webpack</li></ul><h4>Disadvantages:</h4><ul><li>When you need to debug something in the browser console (since the source map we generated), you are directed to the JavaScript (the one with require functions), which are already transpiled from TypeScript which sometimes are not readable, but it works just fine.</li></ul><p>You can find the source code till here on the branch webpack-setup-through-javascript in the <a href="https://github.com/RohitLakh/node-ejs-with-typescript-starter-project">repository</a>.</p><h3>Bundling the TypeScript directly into a bundle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*EKZYH1V4LNV_zTP7NTrdtQ.png" /></figure><p>So here, rather than bundling the JavaScript generated through the gulp command, we would be using webpack modules to directly transpile the TypeScript into the JavaScript.</p><p>For that, we need to install ts-loader, it is a TypeScript loader for webpack.</p><pre>npm i -D ts-loader</pre><p>Now in the webpack.config.js file add his code</p><pre>// The base directory that we want to use<br>const baseDirectory = &quot;src&quot;;<br><br>module.exports = {<br>  // The current mode, defaults to production<br>  mode: &quot;development&quot;,<br><br>  // The entry points (&quot;location to store&quot;: &quot;location to find&quot;)<br>  entry: {<br>    &quot;public/js/scripts&quot;: [`./${baseDirectory}/public/ts/scripts`],<br>     // &quot;other output points&quot; : [&quot;other entry point&quot;] <br>  },<br>  // Using the ts-loader module<br>  module: {<br>    rules: [<br>      {<br>        test: /\.tsx?$/,<br>        use: &quot;ts-loader&quot;,<br>        exclude: /node_modules/,<br>      },<br>    ],<br>  },<br>  resolve: {<br>    extensions: [&quot;.tsx&quot;, &quot;.ts&quot;, &quot;.js&quot;],<br>  },<br>  // Used for generating source maps (used for debugging)<br>  devtool: &quot;eval-source-map&quot;,<br><br>  // The location where bundle are stored<br>  output: {<br>    filename: &quot;[name].js&quot;,<br>  },<br>};</pre><p>Things to notice here:</p><ol><li>The baseDirectory is src now</li><li>A module and resolve object is added.</li></ol><p>So now if we run this it would work, but now the public/ts directory is getting transpiled twice, one with the gulp task &quot;typescript&quot; and one with webpack.</p><p>So, to change that let’s go the gulpfile.js, here on the TypeScript task, we need to exclude the public/ts directory since that would be done anyway by webpack.</p><pre>tsProject.config[&#39;exclude&#39;] = [&quot;./src/public/ts/**/*&quot;]</pre><p>So the TypeScript task would look like this.</p><pre>gulp.task(&quot;typescript&quot;, function () {<br>    tsProject.config[&#39;exclude&#39;] = [&quot;./src/public/ts/**/*&quot;]<br>    return tsProject.src().pipe(tsProject()).js.pipe(gulp.dest(&quot;dist&quot;));<br>});</pre><p>Now if you run the server by npm run dev, you can access the browser console and see the Professor object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sOpjdAdTaFFurj5S.png" /></figure><p><strong>Congrats, you just made use of TypeScript for the frontend.</strong></p><h4>Advantages:</h4><ul><li>While debugging the code in the browser console, you are directed to the TypeScript file (considering you have enabled the sourceMap: true in the tsconfig.json file), rather than the transpiled JavaScript file. This way, you know exactly the line that caused the issue.</li></ul><h4>Disadvantages:</h4><ul><li>A little longer build time as compared to the previous method.</li></ul><p>You can find the source code till here on the branch webpack-setup-through-typescript in the <a href="https://github.com/RohitLakh/node-ejs-with-typescript-starter-project">repository</a>.</p><p>What you can do is shift between the two when you find the required situation.</p><p>If you need any help, let me know in the comment section below</p><p><em>Originally published at </em><a href="https://rohitlakhotia.com/blog/nodejs-ejs-typescript-using-gulp-webpack/"><em>https://rohitlakhotia.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=135aeb93165" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/setup-node-js-ejs-with-typescript-using-gulp-and-webpack-135aeb93165">Setup Node.js, EJS with TypeScript using Gulp and Webpack</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Ghost SSL with multiple domains]]></title>
            <link>https://levelup.gitconnected.com/configuring-ghost-ssl-with-multiple-domains-2fc182d4552f?source=rss-e4cf57fe9df6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fc182d4552f</guid>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[ghost-cms]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[cms-development]]></category>
            <dc:creator><![CDATA[Rohit Lakhotia]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 02:46:49 GMT</pubDate>
            <atom:updated>2024-12-11T15:14:56.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*YCyy9ymFL1JyASTX7Kq2Yw.png" /></figure><p><em>This post was originally published at </em><a href="https://rohitlakhotia.com/"><em>rohitlakhotia.com</em></a></p><p>This tutorial assumes that you have a self-hosted ghost installation up and running.</p><p><a href="https://www.contenttoolkit.co/tool/ghost">Ghost</a> only server content on one domain at a time, so in order to serve content from other domains you need to redirect (<a href="https://www.seoclarity.net/resources/knowledgebase/use-301-redirect-vs-302-redirect-15683/">301 vs 302</a>) that domain to the domain where the ghost CMS is hosted on.</p><p>You may wish to have multiple domains that redirect to your site, e.g. to have an extra TLD or to support www. domains. This is intentional for SEO purposes, however, you can always redirect extra domains to your Ghost install using Nginx.</p><p>If you want to redirect an HTTPS domain, you must have a certificate for it.</p><h3>Basic Setup</h3><p>What we will try to achieve here is to have <strong>www.rohitlakhotia.com </strong>point to the root domain <strong>rohitlakhotia.com </strong>with an SSL certificate so the browser doesn’t show warnings while visiting any of the above.</p><p><em>This would also include the HTTP version to redirect to the HTTPS version so the search engine doesn’t consider them duplicate pages.</em></p><h3>Configure your secondary domain</h3><p>We would need to configure the domain DNS records in order to let the browser know where to go while requests are being made.</p><h3>Configure your domains with proper records</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9pXEjITKpTHZpWW.png" /></figure><p>If you look closely the <strong>www</strong> version and the <strong>@ (root)</strong> version both point to the <strong>same IP (server)</strong>.</p><p>Basically, every request that points to those two versions would be handled by the server at that IP address. Which is exactly what we want. So we can handle them appropriately.</p><p>Now we would need to SSH into the server to install the certificate and properly redirect the domain.</p><p>After you have access to the server, go to the directory where you have installed ghost. Mostly it would be <strong>/var/www/&lt;your ghost installation&gt;</strong></p><p>So <strong>cd</strong> into the directory and then</p><pre>ghost config url https://www.rohitlakhotia.com</pre><p>In place of <strong>www.rohitlakhotia.com</strong>, add your <strong>domain (secondary domain)</strong> that you <strong>want to redirect to the root domain</strong>.</p><p><strong><em>Before proceeding with the next command just make sure that the A records are successfully updated, else the SSL certificate won’t be installed.</em></strong></p><pre>ghost setup nginx ssl</pre><p>This will generate SSL certificates for your domain (which for me is www.rohitlakhotia.com) that you just added and also the Nginx configuration file for the HTTP and HTTPS version. (Easy!)</p><p>Now we will again change the ghost installation URL back to the old one which for me is https://rohitlakhotia.com</p><pre>ghost config url https://rohitlakhotia.com</pre><p>Now we would need to update the newly created Nginx configuration file so that we can redirect the user to the root domain.</p><p>The Nginx configuration files are mostly located at <strong>/etc/nginx/sites-available</strong></p><pre>cd /etc/nginx/sites-available</pre><p>Here you will find all the Nginx configuration files. There should be a minimum of 4 files. Every domain has files with &lt;domain&gt;-ssl.conf (For HTTPS) and &lt;domain&gt;.conf (For HTTP).</p><p>So we would have 4 files:</p><ol><li>rohitlakhotia.com-ssl.conf</li><li>rohitlakhotia.com.conf</li><li>www.rohitlakhotia.com-ssl.conf</li><li>www.rohitlakhotia.com.conf</li></ol><p>Now we need to edit the files for the secondary domain.</p><p>So the files that I need to edit would be <strong>www.rohitlakhotia.com-ssl.conf</strong> and <strong>www.rohitlakhotia.com.conf</strong></p><p>We need to add this line of code inside the location block but at the end.</p><pre>return 301 https://rohitlakhotia.com$request_uri;</pre><p>You can change the 301 to 302 depending on your use case (<a href="https://www.seoclarity.net/resources/knowledgebase/use-301-redirect-vs-302-redirect-15683/">301 vs 302</a>). You will replace rohitlakhotia.com with your primary domain.</p><p>What this line would do is whenever a request is made to the secondary domain then it would redirect (301/302) it to the specific URL.</p><p>So both the files should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VxFssJG1klIc2Iom.png" /><figcaption>www.rohitlakhotia.com.conf</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VCbgzkTxpAu-vy_n.png" /><figcaption>www.rohitlakhotia.com-ssl.conf</figcaption></figure><p>Now check if the configuration files are valid by</p><pre>sudo nginx -t</pre><p>If it’s successful then reload the Nginx server</p><pre>sudo nginx -s reload</pre><p>And that’s it.</p><p>You just pointed your secondary domain to your primary domain in ghost.</p><p><em>For more content, you can check out my </em><a href="https://rohitlakhotia.com/blog"><em>blog</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc182d4552f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/configuring-ghost-ssl-with-multiple-domains-2fc182d4552f">Configuring Ghost SSL with multiple domains</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>