<?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 Darshil Rathod on Medium]]></title>
        <description><![CDATA[Stories by Darshil Rathod on Medium]]></description>
        <link>https://medium.com/@darshilrathod0?source=rss-ea8730d98ff8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2hP4YQT0_tundrUIvR4gdA.jpeg</url>
            <title>Stories by Darshil Rathod on Medium</title>
            <link>https://medium.com/@darshilrathod0?source=rss-ea8730d98ff8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:55:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darshilrathod0/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[Upload data to a user’s Google Drive from the backend (Express JS + React Native)]]></title>
            <link>https://medium.com/@darshilrathod0/upload-data-to-a-users-google-drive-from-the-backend-express-js-react-native-d53fcc2da003?source=rss-ea8730d98ff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53fcc2da003</guid>
            <category><![CDATA[node-js-framework]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[uploading]]></category>
            <dc:creator><![CDATA[Darshil Rathod]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 12:57:39 GMT</pubDate>
            <atom:updated>2023-11-04T13:08:32.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNXb1j41UIYMq65nqsIauw.png" /></figure><p>While building a project recently I had a specific requirement of uploading a file to the user’s Google Drive. The flow was to do a Google login on the React Native app and send the idToken to the backend for authentication and accessing the user’s drive to upload a specific file.</p><p>While the same file could be uploaded from the React Native app itself that might introduce a lot of edge cases for the upload to fail. For example, low internet speed or low-end devices might struggle to upload the file, and the system was highly dependent on this file to be present on the user’s drive for the entire app and the system to work.</p><p>I thought it would be a simple flow that many would have implemented and written articles about but apparently, it wasn’t so easy. Upon doing some research most of the articles I found showed how to upload files to a specific account and not the user’s drive.</p><p>That is what made me dig into this issue and finally write an article about it.</p><blockquote>NOTE: This article can be referred to even if you are using some other frontend/backend framework since the Google procedures will remain the same</blockquote><h3>Premise</h3><p>We are running a React Native app that is using <a href="https://www.npmjs.com/package/@react-native-google-signin/google-signin">@react-native-google-signin/google-signin</a> for performing Google login. We want to access the same user’s Google Drive to upload a JSON file from the backend. On the Express JS backend, we want to use <a href="https://www.npmjs.com/package/googleapis">googleapis</a> npm package for identity verification and access to the user’s Google Drive.</p><h3>What exactly do we wanna achieve?</h3><p>After the idToken is verified by the backend we wanna access the user’s Google Drive to upload a JSON file that contains some user-specific details. This file will be later accessed for performing certain transactions.</p><h3>Setting up the frontend</h3><p>Irrespective of whether you are using React Native or any other platform if there is a package for Google login then you can follow along.</p><p>For this use case, I’m using <a href="https://www.npmjs.com/package/@react-native-google-signin/google-signin">@react-native-google-signin/google-signin</a>.</p><p>From <a href="https://console.cloud.google.com/">Google Developer Console</a> &gt; APIs &amp; Services &gt; Credentials you’ll have to create an OAuth 2.0 Client ID of type Web Application. After creation, you’ll get your webClientId which you’ll use with your package that is being used for Google login.</p><pre>import {GoogleSignin} from &#39;@react-native-google-signin/google-signin&#39;;<br><br>GoogleSignin.configure({<br>      webClientId:<br>        &#39;160004845895-0nkbicsfnkncv537pp75b8g0h7h5hnro.apps.googleusercontent.com&#39;,<br>      scopes: [&#39;https://www.googleapis.com/auth/drive&#39;],<br>    });</pre><p>Using the .configure method you’ll have to provide the webClientId and the scopes.</p><h3>Brief understanding of what scopes are</h3><p>By default, if you don’t provide any scope you’ll get the user’s firstname, lastname, email, and profile picture. That’s all you have access to by default. In case you need extra permissions such as in our case where want to access the user’s Google Drive we need to provide a scope for it.</p><p>Scope for accessing user’s Google Drive:</p><pre>https://www.googleapis.com/auth/drive</pre><p><a href="https://developers.google.com/identity/protocols/oauth2/scopes">Here’s a detailed list of all the available scopes</a></p><p>Once you have added the webClientId and scope you’ll have to call the GoogleSignin.getTokens() method. This method will return an idToken and accessToken that you’ll have to pass to the backend via an API call.</p><h3>Setting up Backend</h3><p>For Node JS there is a package called <a href="https://www.npmjs.com/package/googleapis#oauth2-client">googleapis</a> which is a simple wrapper for accessing Google’s APIs easily. There should be similar packages for other languages and frameworks as well.</p><p>To continue forward we’ll need three things client_id, client_secret, and redirect_url. All this information can be obtained from Google Developer Dashboard &gt; APIs &amp; Services &gt; Credentials and then select your Oauth 2.0 client_id you created while setting up the frontend part.</p><p>Once you have all this just call the following method with these parameters</p><pre>import { google } from &quot;googleapis&quot;;<br><br>const oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);</pre><p>This will create an instance of Oauth2Client, now we need to call one more method for setting the user’s credentials.</p><pre> await oauth2Client.setCredentials({<br>            id_token:<br>                &quot;eyJhbGciOiJSUzI1NiIsImtpZCI6ImY1ZjRiZjQ2ZTUyYjMxZDliNjI0OWY3MzA5YWQwMzM4NDAwNjgwY2QiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIxNjAwMDQ4NDU4OTUtNzFqMzU4cGZobjBtZG05Y3FodXNhNmd2NDIyN3J2ODMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIxNjAwMDQ4NDU4OTUtMG5rYmljc2Zua25jdjUzN3BwNzViOGcwaDdoNWhucm8uYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDAyMjM5NDM3MTQ1NDYzMTAyNTgiLCJlbWFpbCI6ImRhcnNoaWwuMjAwNDEwMTA3MDYzQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdF9oYXNoIjoid0p0by10NFpKNUxaUHJ3Qm0tMHNQdyIsIm5vbmNlIjoiNkk1VGpXa3lDVmctc29OSjNrakQ0SlhOY3ZHcTdHUU5Vdm00cU9aUkwyRSIsIm5hbWUiOiIwNjMgLSBEYXJzaGlsIFJhdGhvZCIsInBpY3R1cmUiOiJodHRwczovL2xoMy5nb29nbGV1c2VyY29udGVudC5jb20vYS9BQ2c4b2NMTUVMdy1oZWIyNG5zMXJqemtSTkZwTHhuZXRLUVltRklmbDZ4Zy1HTzdoQT1zOTYtYyIsImdpdmVuX25hbWUiOiIwNjMgLSIsImZhbWlseV9uYW1lIjoiRGFyc2hpbCBSYXRob2QiLCJsb2NhbGUiOiJlbiIsImlhdCI6MTY5ODkzNTg4OCwiZXhwIjoxNjk4OTM5NDg4fQ.cPCc90_y0trPgoyXr42qA9nr038V_fPAN2mVeJ-nMcH6DvGWsUMZx6_cRUqUDgT0EgaAK5nrQXiF5tdNmx5wN6exNU1H18RZKs3MJs4o5er3luLOLxE1w0DTTXmk3oPcnxxCaT6oo1BngXLVtUVDDwC03UGEVEc14ZlCJi9PZa6cZqw930zWqSW2pg90Dcz6CIli4Lc82YsYW7DXk4-iHRHqQHTbcEoR-ter_rVVRgaN_ZfpMw4fb7T-Vd3e21ftrwcIHwOSl1WLtxczXjsxBJ82znpUui_qX2i0N37h1WIWZeJUCEHAeXXfSU8LGYpaEZfMTb1P1GALMSefqeDxpg&quot;,<br>            access_token:<br>                &quot;ya29.a0AfB_byBaY8GKESRkmrWM_4Dd8hZwL9tDKs-vDdiqdU-672SFCqvqiuC2V7n4gPzDEqKgEKFb2mDO7s_GI5uqYsRPpPY4fLdmG0mLS63J0DE3ivfbqp7Z_XxpiFLbeb_cUrJhELsPbCmRk-eL-9hConQhzduQ_9O75GbuaCgYKAYwSARASFQGOcNnCRirxIDeiDaRngm35_DNu0g0171&quot;,<br>        });</pre><p>By calling the oauth2Client.setCredentials method we’ll pass the user’s id_token and access_token that the client device will send.</p><pre>const { google } = require(&quot;googleapis&quot;); <br><br>const service = google.drive({ version: &quot;v3&quot;, auth });</pre><p>By calling google.drive method we’ll get an instance from which we can access the user’s drive.</p><p>After this there are just two steps, creating the folder and uploading our JSON file to the newly created folder.</p><pre>const fileMetadata = {<br>            name: &quot;Folder name&quot;,<br>            mimeType: &quot;application/vnd.google-apps.folder&quot;,<br>        };<br><br>const file = await service.files.create({<br>            resource: fileMetadata,<br>            fields: &quot;id&quot;,<br>        });</pre><p>The above code creates a folder with the name “Folder name”.</p><pre>const jsonFileMetadata = {<br>            name: &quot;file.json&quot;,<br>            parents: [file.data.id],<br>        };<br><br>const media = {<br>            mimeType: &quot;application/json&quot;,<br>            body: readable,<br>        };<br><br>const jsonfile = await service.files.create({<br>            resource: JSON_FILE,<br>            media: media,<br>            fields: &quot;id&quot;,<br>        });</pre><p>You can upload the file in the newly created folder by passing the folder’s ID in the “parents” attribute.</p><p>One last step would be to allow access to Google Drive on your Google Developer Console Project.</p><p>And you are done, hope you found this article helpful. In case you have any questions or queries drop a comment and I’ll try my best to answer it :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53fcc2da003" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Scalable Video Streaming System on AWS]]></title>
            <link>https://towardsaws.com/implementing-a-scalable-video-streaming-system-on-aws-4249ce5e8693?source=rss-ea8730d98ff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4249ce5e8693</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[video-streaming-service]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Darshil Rathod]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 06:46:59 GMT</pubDate>
            <atom:updated>2021-12-09T06:44:48.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRu24Nn4ABoHdoTxVwcF4g.png" /><figcaption>A high-level overview of the entire system</figcaption></figure><p>Recently I came across a YouTube video from Codedamn’s Channel where Mehul Showcased how Codedamn converts the raw videos and makes them ready for mass consumption on <a href="http://codedamn.com/">codedamn.com</a>. The whole system was fascinating for me and I wanted to implement it on my own so through this article I’ll be sharing my implementation of the whole system on AWS.</p><p>The system on a higher level resembles YouTube wherein you upload your video and YouTube provides you with a sharable link that can use by millions to access it.</p><p>I personally had a lot of fun implementing the system and learning how each and every AWS service is integrated with one another to work in harmony and build something scalable</p><p><strong>Table of contents</strong></p><p>Part 1: <a href="#53a8"><strong>High-level overview</strong></a></p><p>Part 2: <strong>Implementation</strong></p><ul><li><a href="#001a">Step 1: Setting up SQS Queue</a></li><li><a href="#71f5">Step 2: Creating S3 buckets</a></li><li><a href="#e241">Step 3: Setting up EC2 Instance</a></li><li><a href="#1fe0">Step 4: Creating Image(AMI) from EC2 instance</a></li><li><a href="#2f34">Step 5: Creating Launch Configuration</a></li><li><a href="http://0.0.28.215/">Step 6: Creating Auto Scaling Group(ASG)</a></li><li><a href="#95d1">Step 7: Creating Cloudwatch Alarms</a></li><li><a href="#d41a">Step 8: Creating Auto Scaling Group Policies</a></li><li><a href="#6786">Step 9: Creating Cloudfront Distribution</a></li></ul><p>Part 3: <a href="#ea83"><strong>Improvements in the implementation</strong></a></p><h3>AWS Components</h3><ul><li><strong>S3 </strong>Bucket for storing raw and processed video</li><li><strong>Simple Queue Service</strong> (SQS) for message delivery</li><li><strong>Cloud watch</strong> alarms for controlling Auto Scaling Group</li><li><strong>EC2 instances</strong> for processing the video and converting it to multiple formats/bitrates</li><li><strong>ASG(Auto Scaling Group) </strong>for managing EC2 instances</li><li><strong>Cloudfront </strong>for distribution/Caching</li><li><strong>FFMPEG </strong>for conversion of videos into multiple formats and bitrates</li></ul><h3>High-level journey of an unprocessed video to being processed</h3><ul><li>Once the video is upload to S3,<strong> the S3 </strong>bucket will send a message which will include all the details regarding the uploaded video to <strong>SQS</strong></li><li>Once our SQS queue has more than 0 messages a Cloudwatch Alarm will be fired. Cloudwatch will observe the number of visible messages every 1 minute</li><li>Once the alarm is fired it will execute a policy in the Auto Scaling group for increasing an instance in the pool</li><li>Once the instance is launched it will pull our script from GitHub which will contain all the code for copying the newly added video from the unprocessed video’s bucket into the running instance and executing the FFMPEG commands for converting to different formats and bitrates and finally uploading the processed videos to the other S3 bucket</li><li>Once the video is processed we’ll access the video via Cloudfront which will provide us with a layer of caching</li></ul><h3>Step 1: Setting up SQS Queue</h3><p>We’ll be using SQS for storing messages which will contain details regarding the video that is supposed to be processed</p><ul><li>After opening the SQS Page on AWS we’ll create a new queue</li><li>For our requirements, a standard queue will work just fine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sllkD5kCtg8KVpZXDnROYQ.png" /><figcaption>Details section in SQS</figcaption></figure><ul><li>Keeping everything at default except <strong><em>Visibility timeout</em></strong> since the amount of time required for processing videos will depend on the video’s size and format along with the configuration of the EC2 instances we select and the number of final versions we process into. Accounting all of that for my requirements 2 hours was a good enough time</li><li>If you don’t know the exact time, make sure you keep the value higher than you think it will take to process, we’ll discuss more on this…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPOku5kIF_cjUuGRzwzumg.png" /><figcaption>Configurations for SQS</figcaption></figure><ul><li>Keeping the rest of the settings on default we’ll click on <em>Create queue.</em></li></ul><p><strong>A quick recap on some SQS Terminologies</strong></p><ul><li>Messages available: Messages which are yet to be processed</li><li>Messages in flight: Messages which are currently being worked on by some service</li><li>Visibility timeout: Time for which a message becomes invisible (In-flight) before becoming visible again</li></ul><h3><strong>Step 2: Creating S3 buckets</strong></h3><p>We’ll be storing all the unprocessed and processed files in 2 separate buckets</p><p><strong>Bucket for storing unprocessed videos</strong></p><ul><li>Start off by simply creating an S3 bucket with all the default settings except the “Block Public Access Policy”</li><li>Uncheck the <em>Block all public access </em>so that you can access the bucket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*RwVnKNSzYnmCpZRNRXbfLQ.png" /><figcaption>Public access policy</figcaption></figure><ul><li>Once the bucket is created, head over to the <strong><em>Properties </em></strong>tab and scroll down to <strong><em>Event notifications</em></strong></li><li>Create an event notification so that every time we upload a new file, our S3 bucket can send a message to the SQS service</li><li>In the <strong><em>Create event notification </em></strong>section give it a name and inside <strong><em>Event types </em></strong>tick on <strong><em>All object create events </em></strong>so that we only get a notification when we upload a new file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*WH89c_VYbus6EDERl2QJ_g.png" /><figcaption>Event types section</figcaption></figure><ul><li>In the <strong><em>Destination</em></strong> tab, we’ll select <em>SQS queue </em>as our<em> destination </em>and select the queue that we just created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*mgHDcUmc8bVDTaOaQSeRAA.png" /><figcaption>Destination Section</figcaption></figure><ul><li>After saving we are done connecting our RAW Videos S3 bucket to SQS</li></ul><blockquote><strong>Note:</strong> Every time you change some setting in the<strong> Event type</strong> section of the S3 bucket, it will send a confirmation message to SQS so make sure you <strong>removing that message</strong> by either deleting it or purging the queue (under Actions&gt;Purge)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*AcqM--ZSsaQkb-a2qZ2Gyw.png" /><figcaption>Purging the queue</figcaption></figure><blockquote><strong>Note: </strong><em>For making an S3 bucket publicy accessable you’ll also have to change it’s policy, under the </em><strong><em>permissions </em></strong><em>tab in </em><strong><em>Bucket policy</em></strong><em> add the below code and replace BUCKET_NAME_HERE with your own bucket name</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/384a8fc2e2a97dac13a9d451ca0ed1a9/href">https://medium.com/media/384a8fc2e2a97dac13a9d451ca0ed1a9/href</a></iframe><p><strong>Bucket for storing processed videos</strong></p><ul><li>Simply create a bucket with the default settings since we’ll configure it later while setting up Cloudfront</li></ul><h3>Step 3: Setting up EC2 Instance</h3><p>Before moving on to setting up AWS Auto Scaling Group we’ll first configure an EC2 instance with all the required tools like FFMPEG and our scripts</p><ul><li>Go ahead and launch an EC2 instance with the following configuration</li></ul><h4>Configurations:</h4><ul><li>OS: Ubuntu (Any version)</li><li>Size: I went with t3.medium which offers (2 CPUs &amp; 4 GB Ram), if you want to go with the free tier then select t2.micro although converting even a 100 MB video might take a very long time</li><li>We’ll have to add an <em>IAM Role </em>but we’ll add it later on</li><li>For storage 8 GB will work until and unless your videos go above it</li><li>Keeping rest as default and you can lunch the instance</li><li>After launching, update the instance and <a href="https://linuxize.com/post/how-to-install-ffmpeg-on-ubuntu-18-04/">install FFMPEG</a></li></ul><p><strong>Creating IAM Role for EC2 instances</strong></p><p>Since our EC2 instances will be accessing the S3 buckets for getting the unprocessed videos and after processing uploading them to the other bucket, we’ll have to provide them with an IAM Role</p><p>Here are the steps to make an IAM Role that will allow our EC2 instance to access the S3 buckets</p><ul><li>After visiting the IAM Role’s page click on <em>Create role</em></li><li><em>Select type of trusted entity</em> as <em>AWS Services</em></li><li><em>Choose a use case</em> as <em>EC2</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*BNYrZo4gBEDxrTAsKKGdCg.png" /><figcaption>Create role section</figcaption></figure><ul><li>In the <em>Attach permissions policies</em> section search for <strong><em>AmazonS3FullAccess</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*XJSQzhxPmX6TeBrf3wxxMQ.png" /><figcaption>Giving full access to EC2 for accessing S3</figcaption></figure><ul><li>After hitting create we are done setting up an IAM Role which will allow our EC2 instances to access the S3 buckets</li></ul><p><strong>Setting up a Script</strong></p><p>Once our EC2 instance is up and running we want to run some commands which will fetch the raw video and run it through FFMPEG and spit out our required processed videos which we’ll upload back to the other bucket</p><blockquote><strong><em>Note: </em></strong><em>For this project I have used a </em><strong>shell script</strong><em> but I would highly recommand you to go with a </em><strong>Javascript or Python script</strong><em> for performing the following task, more on that later…</em></blockquote><p><strong>Here’s the shell script that I came up with, it’s not perfect and there are flaws in it like no error handling, if I had to deploy this project then I would prefer using Javascript or Python Script or even shell script only but with error handling</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560a6167a2bf6c8493b66753f74d6670/href">https://medium.com/media/560a6167a2bf6c8493b66753f74d6670/href</a></iframe><p><strong>Understanding the shell script commands</strong></p><pre>var7=$(ec2metadata --instance-id)</pre><ul><li>In var7 we’ll be storing the <em>instance id</em> of the instance that is running this script, we’ll use this to place an <strong><em>instance protection </em></strong>lock on the instance that is running this script so that our instance is not terminated by Auto Scaling Group while the video conversion is happening</li></ul><pre>aws autoscaling set-instance-protection --instance-ids $var7 --auto-scaling-group-name AUTOSCALING_GROUP_NAME --protected-from-scale-in</pre><ul><li>AUTOSCALING_GROUP_NAME: Replace this with our Auto Scaling Group name</li><li>- — protected-from-scale-in this line places a termination lock on the instance to prevent ASG from terminating it</li></ul><pre>main_obj=$(aws sqs receive-message --queue-url YOUR_QUEUE_URL --attribute-names All --message-attribute-names All --max-number-of-messages 1)</pre><ul><li>YOUR_QUEUE_URL: Replace this with our SQS Url</li><li>Via this command, 1 message is taken from SQS and stored into a variable named <strong><em>main_obj </em></strong>(Message is in JSON Formate)</li></ul><pre>echo -e $main_obj &gt; version.json</pre><ul><li>A <strong><em>version.json </em></strong>file<strong><em> </em></strong>is created from the data stored in the main_obj variable</li></ul><pre>var1=$(jq &#39;.Messages[] | {Body} | .Body | fromjson | . | .Records[] | {s3} | .s3 | .bucket | .name&#39;  version.json)  </pre><pre>var2=$(jq &#39;.Messages[] | {Body} | .Body | fromjson | . | .Records[] | {s3} | .s3 | .object | .key&#39;  version.json)</pre><ul><li>We’ll be using a command-line tool known as <a href="https://stedolan.github.io/jq/">JQ</a> for accessing data from the newly created version.json file</li><li><strong><em>var1</em></strong> will be storing the name of the bucket while <strong><em>var2 </em></strong>will be storing the name of the video file</li></ul><pre>var3=$(echo s3://$var1/$var2 | tr -d &#39;&quot;&quot;&#39;)</pre><ul><li>For using AWS CLI for copying files from the S3 bucket you’ll require <em>S3 URI </em>which we’ll construct using the bucket name and filename</li><li>The file S3 URL will be of the formate: s3://BUCKET_NAME/FILE_NAME</li><li>By default since it’s a string, it will have inverted commas(“ “) which we’ll remove using the command tr -d &#39;&quot;&quot;&#39;</li></ul><pre>var4=$(echo $var2 | tr -d &#39;&quot;&quot;&#39;)</pre><ul><li>We’ll also store the name of the file without the inverted commas in a variable named <em>var4</em></li></ul><pre>var5=$(echo $var4-1080.mp4) </pre><pre>var6=$(echo $var4-720.mp4)</pre><pre>#This might sound like a hack but that’s how I got it working :)</pre><ul><li>For the naming of newly converted files, I’m using a naming convention of ORIGINAL_FILE_NAME-RESOLUTION.mp4</li></ul><pre>aws s3 cp $var3 $var4</pre><ul><li>Using this command we’ll provide the S3 URL and the file name to copy the RAW Video from S3 into the instance for processing</li></ul><pre>ffmpeg -i $var4 -filter:v &quot;scale=w=1920:h=-1&quot; -b:v 6M $var5 </pre><pre>ffmpeg -i $var4 -filter:v &quot;scale=w=1280:h=-1&quot; -b:v 3M $var6</pre><ul><li>We’ll be using FFMPEG for conversion so with these commands we’ll scale down the video to 1920x1080 (6 MB/s) and 1280x720 (3 MB/s)</li><li>Here you can specify all the resolutions, bitrates and formats you want a particular video to be converted</li></ul><pre>aws s3 cp $var5 YOUR_S3_BUCKET_URL</pre><pre>aws s3 cp $var6 YOUR_S3_BUCKET_URL</pre><pre>#This is how an S3 URL Looks: s3://video-streaming-output-bucket</pre><ul><li>Once the videos are converted into multiple formats we’ll upload them to an S3 Bucket (that we made for processed videos)</li></ul><pre>var8=$(jq &#39;.Messages[] | {ReceiptHandle} | .ReceiptHandle&#39;  version.json) </pre><pre>receipt_handle=$(echo $var8 | tr -d &#39;&quot;&quot;&#39;)</pre><ul><li>Using the above commands will get the <strong><em>ReceiptHandle </em></strong>of the message from the version.json file and remove the inverted commas</li></ul><pre>aws sqs delete-message --queue-url https://sqs.ap-south-1.amazonaws.com/968225076544/video-streaming --receipt-handle $receipt_handle</pre><ul><li>Using this command we’ll pass in our <strong><em>ReceiptHandle </em></strong>and delete the message from SQS</li></ul><pre>aws autoscaling set-instance-protection --instance-ids $var7 --auto-scaling-group-name AUTOSCALING_GROUP_NAME --no-protected-from-scale-in</pre><ul><li>AUTOSCALING_GROUP_NAME: Replace this with our Auto Scaling Group name</li><li>Since our processing is completed and we no longer need the instance we’ll remove the termination lock so that ASG can terminate it</li></ul><p><strong>Here’s a preview of the message that you’ll receive from SQS</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34646164c49e95661879e8688c45016d/href">https://medium.com/media/34646164c49e95661879e8688c45016d/href</a></iframe><p><strong>Setting up our EC2 instance to run the script automatically on the startup</strong></p><p>By this point, we have completed the setup on one EC2 instance wherein we can simply run a shell script and the RAW video will be pulled, converted and uploaded back but only we’ll have to automate the script running part so we’ll make some changes in Ubuntu so that it automatically runs a script when it boots up</p><p>Configuring Ubuntu to run a shell script on startup</p><p><strong>Step: 1</strong></p><ul><li>Go to <strong><em>/etc </em></strong>from the root directory</li></ul><p><strong>Step: 2</strong></p><ul><li>Create a file with the name <strong><em>rc.local </em></strong>in <strong><em>/etc </em></strong>directory</li><li>Once the file is created we’ll paste the following code into it</li></ul><pre>#!/bin/bash</pre><pre>git clone YOUR_GITHUB_URL</pre><pre>cd PROJECT_FILE</pre><pre>bash SCRIPT.sh</pre><ul><li>Okay you might be confused with all this and it’s okay</li><li>We can directly paste the script that we just created into the rc.local file but every time you update the script by adding a new video format, you’ll have to stop the running instances and set everything up again</li><li>To eliminate that we save our shell script on GitHub and via the shell script present in the rc.local file we just pull that script from Github and execute it</li><li>Now every time you make some change to the script, you’ll only have to push it to Github and that’s it</li><li>After creating the rc.local file just run the following command</li></ul><pre>sudo chmod a+x /etc/rc.local</pre><h3>Step 4: Creating Image(AMI) from EC2 instance</h3><p>Now everything we need in order to perform our task of converting a raw video into multiple processed versions is set up on one EC2 instance. Now we want to make it so that every time ASG launches a new instance it has all this data in it. In order to do that we’ll create an image of the instance that has everything installed and save it for further use</p><p><strong>Steps for creating an Image(AMI)</strong></p><p>Step 1: Select the instance which has everything set up and click on <strong><em>Create image</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*5_ZsTBl1_MseiyuCuMtznA.png" /><figcaption>Creating an image from an EC2 instance</figcaption></figure><p>Step 2: Enter the image name and keep everything else as default</p><h3>Step 5: Creating Launch Configuration</h3><p>Once the image is created, we now have all the data required for the processing but we’ll still have to specify the rest of the things like the size of the instance (t2.medium or t3.large), networking and security related things. Basically, we’ll tell Auto Scaling Group with which configurations do we want to launch our instance</p><p><strong>Steps to create a Launch Configuration</strong></p><ul><li>Head over to the <strong>EC2 page on AWS</strong> and go to the <strong>Auto Scaling Group</strong> section on the left side of the drawer and select <strong>Launch Configuration</strong></li><li>Enter the name and select the <strong>AMI </strong>that we just created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elAc7IvMIK_IrTL3FdS9YQ.png" /><figcaption>Creating launch configuration</figcaption></figure><ul><li>Click on Choose instance type and select a type that will suffice your requirements</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*x9GKgzIST-kY4D2zMS2BZw.png" /><figcaption>Select instance size</figcaption></figure><ul><li>In the <strong>IAM instance profile</strong> section under <strong>Additional configuration</strong> select the IAM Role that we had created</li><li>This will give all our EC2 instances launched by ASG the permission to access our S3 buckets</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYm6HFBZiUW6LwcQxoNYUQ.png" /><figcaption>Giving IAM Role</figcaption></figure><ul><li>After adding <strong>Security groups</strong> &amp; <strong>Key pair (login) </strong>click on<strong> </strong>Create launch configuration</li></ul><h3>Step 6: Creating Auto Scaling Group(ASG)</h3><p>ASG will be controlling the spawning and termination of EC2 instances, so in cases where there are multiple messages in the queue ASG can simultaneously launch multiple instances and all of the videos can be processed parallelly</p><ul><li>Start by creating an Auto Scaling Group, enter the name of the ASG and <strong>Switch to launch configuration</strong> and select the launch configuration that we just created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XurQyUfIAA1iOuvmDFCgg.png" /><figcaption>Creating Auto Scaling Group</figcaption></figure><ul><li>In the <strong>Configure settings </strong>tab select the required subnets</li><li>In the <strong>Configure advanced options </strong>keep everything as default for now</li><li>In <strong>Configure group size</strong> <strong>and scaling policies</strong> under <strong>Group size</strong> select the following</li></ul><p><strong>Desired Capacity:</strong> <strong>0</strong> (We do not want any instance running while there are no videos to process)</p><p><strong>Minimum Capacity: 0 </strong>(We ideally want to keep the number of instances to 0 if there are no videos to process)</p><p><strong>Maximum Capacity: 3</strong> (Here you can select the max number of instances you want to launch simultaneously if there are multiple videos to process at a given moment)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*KekrQQ5diOOcAxikvDB2Zg.png" /><figcaption>Selecting configuration for Auto Scaling Group</figcaption></figure><ul><li>You can leave <strong>Scaling policies</strong> to none, for now, we’ll add them later</li><li>Keeping the rest of the things as default we can create the ASG</li><li>We’ll create the scaling policies after creating the Cloudwatch Alarms</li></ul><h3>Step 7: Creating Cloudwatch Alarms</h3><p>Cloudwatch will continuously watch our SQS for messages, once there are more than 0 messages, meaning someone uploaded a video for processing, it can fire a scaling policy in ASG which we’ll be creating soon and vice versa once the number of visible messages goes to 0 it will fire another ASG policy which will reduce the EC2 instances</p><p><strong>Policy for increasing the instances</strong></p><ul><li>Start off by clicking on Create alarm, for the metric we’ll be going with <strong>Approximate Number of Messages Visible</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxeQYfFL8Ou6GEOQvV8czw.png" /><figcaption>Selecting Cloudwatch metric</figcaption></figure><ul><li>In the next section, we’ll change the Period to 1 minute</li></ul><blockquote><strong>Reason behind keeping Period as 1 minute</strong> :<em> While testing out the system I have calculated that it takes </em><strong><em>less than 1 minute</em></strong><em> for the shell script to run and mark a message in SQS as </em><strong><em>In filght message</em></strong><em>. What that means is if we uploaded only 1 video for processing then after the Cloudwatch alarm is fired, under 1 minute the EC2 instance will be up and mark that message as </em><strong><em>in flight</em></strong><em> so that the next time(after 1 minute) Cloudwatch checks for the </em><strong><em>number of messages visible</em></strong><em> it will get 0, signalling there are no more videos to process.</em></blockquote><ul><li>Moving further in the <strong>Conditions</strong> section keep it <strong>Greater than 0</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ID39_3aVDmjpCE_fToxrmQ.png" /><figcaption>Selecting threshold for alarm activation</figcaption></figure><p><strong>Policy for reducing the instances</strong></p><p>The above alarm is set in a way that will keep launching EC2 instances while there are messages in SQS for processing videos. Once the number of visible messages drops to zero the above alarm will become inactive and that is when we fire this particular alarm that we’ll create now for reducing the instances</p><ul><li>Start off by clicking on <strong>Create alarm</strong>, for the metric we’ll be going with <strong>Approximate Number of Messages Visible </strong>just as last time</li><li>But the main change will be in the Conditions section, for this alarm we’ll fire it once there is less than 1 message(i.e. 0 messages) signalling no more instances needed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*ZzeWKT9TvmIgVkXzvFuwYQ.png" /><figcaption>Selecting threshold for alarm activation</figcaption></figure><blockquote><strong>Reminder: </strong><em>By this point if you are confused about the alarms and how they’ll work then don’t worry we’ll be tying everything up in next section where we’ll be creating some policies</em></blockquote><h3>Step 8: Creating Auto Scaling Group Policies</h3><p>Using the Cloudwatch alarms we just created we’ll fire these policies and they will do the actual task of increasing the decreasing the instances</p><p><strong>Creating a policy that will increase the number of instances</strong></p><ul><li>In the ASG under the <strong>Automatic Scaling</strong> tab click on <strong>Create dynamic scaling policy</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLJqau-UPjZQJu6TapKbpg.png" /><figcaption>Creating Dynamic Scaling Policy</figcaption></figure><ul><li>For this particular policy will be going with <strong>Step Scaling</strong></li></ul><p><strong>Why Step Scaling?</strong> Because every time the alarm is fired we want to increase the number of instances by just 1</p><ul><li>Now select the alarm that we just created for increasing the number of instances (for me the name is <strong>add-one)</strong></li><li>For <strong>Take the action</strong> select <strong>add </strong>since we want to add an instance</li><li>In the <strong>Capacity units</strong> select <strong>1</strong></li><li>Keep the <strong>seconds warm up before including in metric</strong> as 120 seconds</li></ul><p><strong>Why 120 seconds?</strong> Since our instance takes less than 1 minute to place the termination lock we can go with any number of seconds greater than 60 seconds so that the termination lock is placed in time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*HrJ3kBvGpbYVWEaIHtumGQ.png" /><figcaption>Step scaling policy for increasing and instance</figcaption></figure><p><strong>Creating a policy that will decrease the number of instances</strong></p><ul><li>In the ASG under the <strong>Automatic Scaling</strong> tab click on <strong>Create dynamic scaling policy</strong></li><li>This time we’ll be going with<strong> Simple scaling</strong></li></ul><blockquote><strong><em>Reason for going with Simple Sacling:</em></strong> <em>This particular policy will be fired only when there are no more visible messages in </em><strong><em>SQS</em></strong><em>, meaning no more videos need to be processed. Once the alarm is fired and this policy is executed we’ll set the number of desired instances to 0.</em></blockquote><blockquote><strong><em>Won’t the runnning instances also get terminated? </em></strong><em>Answer is no and you might have gussed it, since we are placing a termination lock (turning on </em><strong><em>instance protection</em></strong><em>) when the instance is first started ASG won’t be able to terminate it. Once the processing is completed we’ll lift the termination lock (turning off </em><strong><em>instance protection</em></strong><em>) and thus allowing ASG to terminate it</em></blockquote><ul><li>For the Cloudwatch alarm select the one that we created for reducing the number of instances (for me the name is <strong>remove-one,</strong> I know the name is confusing but you can select a better name :)</li><li>For <strong>Take the action</strong> select <strong>Set to</strong> as 0</li><li>For the <strong>waiting period</strong> you can select 10 sec since this particular metric won’t be affecting our system</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*0eDdjTFblhRmnR94W3AjAw.png" /><figcaption>Simple scaling policy to set the number of desired instances to 0</figcaption></figure><h3>Step 9: Creating Cloudfront Distribution</h3><p>By this point we have completed the whole video uploading and converting system and automated it, we’ll now move towards distribution</p><p><strong>Why Cloudfront?</strong></p><p>We can directly use the S3 URLs and it will definitely work but S3 not only charges you for the amount of data you store but also the amount of data transfer that happens from the S3 bucket</p><p>Plus it’s always better to use caching where ever possible and Cloudfront solve both of them</p><ul><li>Cloudfront offers to cache so that if the data is already available in the cache then the request won’t go to the S3 bucket and hence<strong> reducing the cost</strong> and <strong>increasing the speeds</strong></li></ul><p><strong>Creating a Cloudfront Distribution</strong></p><ul><li>Start off by visiting the CloudFront page on AWS and clicking <strong>Create Distribution</strong></li><li>For <strong>Origin domain</strong> select the S3 bucket that we created in the beginning for storing processed videos</li><li>Under <strong>S3 bucket access</strong>, select <strong>Yes use OAI</strong>, this will restrict the access to CloudFront only so that no one accesses the files directly from the bucket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*E7N22hwjieasY91yOMvYiA.png" /><figcaption>Setting up Cloudfront</figcaption></figure><ul><li>You can change the rest of the settings as per your requirement but leaving them as default will work too</li><li>With that, we are done with distribution🥳</li></ul><p>After configuring distribution now our system is ready for testing, once you upload a file in the raw video’s S3 bucket, our SQS should receive a message, after 1min our Cloudwatch alarm will fire and an EC2 instance will be launched, after another 1 min when Cloudwatch will check the number of visible messages it will be 0 resulting in the other downscaling alarm to fire and set the number of desired EC2 instance to 0. Once the launched EC2 instance is done processing the video and upload it to the final bucket it will remove the termination lock due to which ASG will terminate the instance and the final processed versions of the video are now ready for mass consumption</p><p>I know the system still needs some crucial components and that is what the next section is going to be :)</p><h3>Improvements</h3><p>At this point, the core functionality is achieved but there are some other aspects to it as well which I would like to discuss and add to a production version</p><p><strong>1. Creating a backend</strong></p><ul><li>Right now we are directly uploading the videos to S3 but we definitely don’t want to do that so I would create a backend that will first <strong>perform some checks</strong> before uploading the video and most importantly after the uploading is completed it will<strong> store the URL in a table </strong>to that we maintain a log of RAW videos</li></ul><p><strong>2. Improving the Shell Script</strong></p><ul><li>The shell script that I have provided <strong>can not be used for anything apart from testing the system</strong>, because of a lack of error handling and not following best practices</li><li>Instead, if I had to deploy this project on an actual workflow(on production) then I would instead make a<strong> Javascript script or a Python script</strong> that would perform the tasks, this way we can have <strong>more control </strong>and most importantly <strong>error handling</strong></li></ul><p><strong>3. Adding a Dead Letter Queue</strong></p><ul><li>If a video for some reason does not get processed after multiple attempts then by setting up a Dead Letter Queue we can shift those messages there and review them manually</li></ul><p><strong>4. Adding more formates</strong></p><ul><li>For demonstration purposes, I have only included 1080p and 720p versions with 8MB/s and 5MB/s bitrate respectively but in a production environment I would have <strong>multiple video formats with different resolutions and bitrates</strong> to serve the content to each and every device</li></ul><p><strong>5. Notifications</strong></p><ul><li>For getting notified when a video is done processing or there is some error, I would add some sort of notification system</li><li>This could be as simple as setting up AWS SNS to send an email with the links of processed video or the error or actually showing the progress on the frontend while the video is getting processed (just like YouTube)</li></ul><p>If you have any suggestions for improving the system then please comment them down below, I would love to read them🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4249ce5e8693" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/implementing-a-scalable-video-streaming-system-on-aws-4249ce5e8693">Implementing a Scalable Video Streaming System on AWS</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>