<?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 sankalp jonna on Medium]]></title>
        <description><![CDATA[Stories by sankalp jonna on Medium]]></description>
        <link>https://medium.com/@sankalpjonna_89229?source=rss-798c05e98697------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lshcZTDEIjJ7EceLSe5Uqg.jpeg</url>
            <title>Stories by sankalp jonna on Medium</title>
            <link>https://medium.com/@sankalpjonna_89229?source=rss-798c05e98697------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:45:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sankalpjonna_89229/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[Hosting your entire web application using S3 + CloudFront]]></title>
            <link>https://medium.com/@sankalpjonna_89229/hosting-your-entire-web-application-using-s3-cloudfront-5dd92c99763f?source=rss-798c05e98697------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd92c99763f</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[sankalp jonna]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 15:36:37 GMT</pubDate>
            <atom:updated>2020-07-12T15:36:37.134Z</atom:updated>
            <content:encoded><![CDATA[<p>There are several ways to host an application on the internet, but the one that I am most familiar with is to use a web server such as Apache or NGINX where you can host all the static components of your application and also use it as a reverse proxy server to direct API calls.</p><p>‍But recently I came across another way to host a web application which is more elegant, cost effective and has no need for maintenance. This method makes use of AWS S3 and AWS Cloudfront and it’s turned out to be significantly easier to set up, scales infinitely and is cheaper than the alternative.</p><p>‍</p><h4>Why did we need S3 to host a web application?</h4><p>The <a href="https://apps.shopify.com/whatsapp-chat-button">product</a> that I have built is currently architected in this way — we use an open source version of Nginx that is hosted on an AWS VPS instance which takes care of hosting our static files for our web app and also works as a reverse proxy server to send API calls to our backend applications.</p><p>This setup worked great so far because we have a limited number of users that need access to the application dashboard and there is no need for a CDN either because the users, especially the ones on a paid plan do not have any problem waiting a couple of seconds more for the website to load.</p><p>This requirement changed when there was a new feature requirement within our product. Our users are e-commerce merchants and most of them accept “Cash on delivery” as an option while accepting orders and this leaves a lot of room for fraud to occur where somebody places an order and selects the payment method as “Cash on delivery” without the intention to actually buy the product.</p><p>In order to fix this we introduced a feature where the customer who places a COD order gets an automated message on WhatsApp to confirm their order via a link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*ytFxBMB9FugCEMp-E0mMUQ.png" /><figcaption>Automated WhatsApp message to confirm a COD order</figcaption></figure><p>Clicking on this link would open this web page‍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*fmOgTObeVoLPjG8E.png" /><figcaption>Reactjs web app used to confirm a COD order</figcaption></figure><p>Now this web page would be accessed by the customers that buy from the merchants that use our application, so the traffic to this page could be very erratic, not to mention the fact that it would come from various parts of the world where the users internet connection would also be erratic and vary according to the region.</p><p>Therefore it did not make sense to host this web page the way the rest of our application is hosted. This web app had the following requirements</p><ul><li>High availability from any part of the world</li><li>Fast load time</li><li>Ability to handle any amount of traffic</li><li>Not having the need to manage or monitor</li></ul><p>It turns out that all of these things can be achieved if you host the app using a combination of S3 and CloudFront which is the CDN offered by AWS.</p><h4>How to host an application on s3</h4><p>There is a comprehensive guide in the AWS documentation on how to do this — <a href="https://docs.aws.amazon.com/AmazonS3/latest/user-guide/static-website-hosting.html">link to documentation</a>.</p><p>The TL:DR for this is to Create an s3 bucket with the same name as the domain/subdomain where you want to host your web app.</p><p>For instance, our web page had to be hosted on cod.superlemon.xyz, so this is what the s3 bucket would be called. After this there are a bunch of properties and settings that you would have to change on the bucket which are mentioned in the doc.</p><p>Once this is done, you can test whether it worked or not by using either of the below links based on the region where you are hosted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*6kmDm__2u7gjw3yo.png" /><figcaption>End points for verifying if the s3 hosting worked or not</figcaption></figure><p>Though the steps in the AWS doc are quite comprehensive, there is one gotcha here that you must keep in mind. If your web app runs on a framework like react which is what we are using, you must make sure that under the “static website hosting” settings of the AWS bucket, you set the index document as well as error document as index.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*H8rP58k3w2dt8j-B.png" /><figcaption>S3 static web hosting settings</figcaption></figure><p>This is to ensure that if you have any URL routes set up in your react application, those routes are honoured.</p><h4>How to put the s3 application behind a CDN</h4><p>The above step only completes one step of the process where your application is now residing in s3. But the process is only complete if the application is accessible as a CDN. For this you would have to use CloudFront and configure it to use your s3 bucket as the source. A comprehensive documentation for this process is given <a href="https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-https-requests-s3/">here</a>.</p><p>There are a few gotchas here as well. The first one being that you will require an SSL certificate to host your application as <a href="https://./"><strong>https://</strong>.</a> You can get an SSL certificate easily using <a href="https://aws.amazon.com/premiumsupport/knowledge-center/install-ssl-cloudfront/">AWS Certificate manager</a>. This process becomes even more easy if you are using Route53 to manage your domains and subdomains. Even if you use another provider like Godaddy or Bigrock for your domains, I would highly recommend following <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/migrate-dns-domain-in-use.html#migrate-dns-change-name-servers-with-provider">these steps</a> to plug in your domains to Route53.</p><p>The other gotcha here is once again something to do with reactjs URL routing. If you are using this in your application, there is another step that you have to follow. Under your CloudFront distribution, you must navigate to error pages and create a new custom error response as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AKsflrw8cA4P1f62.png" /><figcaption>CloudFront distribution error pages settings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*ISLMvY_YG2vp4K80.png" /><figcaption>CloudFront distribution handling 403 error</figcaption></figure><p>This will ensure that if the CDN is not able to find the URL path you specify, it will default to index.html which will handle the routing in case of a reactjs application.</p><p>After finishing all these steps you will receive a url for your CloudFront distribution that looks something like this <a href="https://dohgltcrfo5nj.cloudfront.net/">— dohgltcrfo5nj.cloudfront.net</a>. You just need to use this URL as an alias and map it to your domain/subdomain which in our case is<a href="http://cod.superlemon.xyz/"> cod.superlemon.xyz</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*eTckSmPCVkelOiv0.png" /><figcaption>Route53 subdomain targeting</figcaption></figure><p>And that’s it, it’s done! You now have a highly available application which does not need to be monitored or managed. Once you launch your application this way, it is now on a CDN and if you have to update the application in the future, the CDN cache must be invalidated for the changes to take effect. This can be done under the “invalidations” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GsGKamubpuvreHKO.png" /><figcaption>CloudFront cache invalidation</figcaption></figure><p>Then supply all the paths that have been updated and you would like the CDN cache to invalidate. If you would like to invalidate the entire app, just enter “*”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*uGyflrqSFntHc09I.png" /><figcaption>CloudFront cache invalidation for specific paths</figcaption></figure><h4>Closing notes</h4><p>This approach works great for a use case where the web application is mostly static and can be completely decoupled from the backend applications.</p><p>In terms of cost, with this approach you will only incur the CDN cost since the s3 storage cost for any web application would be quite low and the CDN cost will depend on how much traffic you have so it would scale well with usage.</p><p>For reference, we had around 100k hits on our web page in the month of June and our cost was roughly 0.79$</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zVpH1C-_OJvt3OhE.png" /><figcaption>Our cost for this setup in the month of June</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd92c99763f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our AWS bill is ~ 2% of revenue. Here’s how we did it]]></title>
            <link>https://medium.com/@sankalpjonna_89229/our-aws-bill-is-2-of-revenue-heres-how-we-did-it-e50e47230c7?source=rss-798c05e98697------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50e47230c7</guid>
            <category><![CDATA[bootstrapping]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[amazon-lightsail]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[sankalp jonna]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 07:03:57 GMT</pubDate>
            <atom:updated>2020-06-28T07:07:55.328Z</atom:updated>
            <content:encoded><![CDATA[<p>Server cost is usually not a concern for most funded startups, but for a bootstrapped SaaS product like ours, it was important to have an AWS bill that is easy on the pocket and a little more proportional to the MRR.</p><p>‍To that end when we started <a href="http://superlemon.xyz/">superlemon.xyz</a> one of the first things I did was to find ways to consume the least amount of resources on the cloud. We currently serve a traffic of ~ 250 requests per second with our AWS setup.</p><p>‍Most applications require certain common cloud resources and these include‍</p><ul><li>Compute instances</li><li>Database instances</li><li>Caching instances</li><li>CDN</li><li>A web server that acts as a reverse proxy and load balancer</li></ul><p>‍I will now go through each of these resources and talk about both the expensive way and the cheap way to implement them</p><p><strong>Compute instances</strong></p><p><strong>‍</strong>When it comes to compute instances, most people go with AWS EC2 instances. EC2 instances are the safest choice to make for running server applications as they are highly configurable, scalable and you can change the configuration on demand according to your needs. However, sometimes you do not really need this level of control on your compute instances and that brings us to <a href="https://aws.amazon.com/free/compute/lightsail/">AWS Lightsail</a>.</p><p>‍Lightsail as the name suggests is a lightweight version of EC2. Under the hood Lightsail instances are actually EC2 instances, but this is not apparent to the user and unlike the highly configurable EC2, Lightsail comes with a fixed configuration that once you provision cannot be changed. The billing is also a fixed amount per month as opposed to EC2 which is billed by the hour.</p><p>‍To give you a sense of how much less complicated Lightsail is, please take a look at these screenshots of the EC2 dashboard and Lightsail dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bctzJBd7MkO_DHQE.png" /><figcaption>Lightsail dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wZ7ykNomNxH_rkzj.png" /><figcaption>EC2 dashboard</figcaption></figure><p>But we are not here to debate the complexity of EC2 vs Lightsail, so let’s let us talk about the cost.</p><p>An EC2 instance with 2 virtual cores, 4GB RAM and a storage of 80GB costs roughly 37$ a month and a Lightsail instance with the exact same configuration costs 20$ a month which is almost half the cost!</p><p>‍The only drawback here as previously mentioned is that the instance is fixed and neither the storage nor the compute power can be tweaked later according to spikes in traffic and usage.</p><p>‍In our case we do not have a need for too much storage on the compute instance, and as for the computing power it was easy for us to simply provision another Lightsail instance when there is an increase in traffic and set it up behind a load balancer. This way our system is still scalable.</p><p><strong>Database instances</strong></p><p>Choosing a database provider for your application can be a tricky decision, but on a high level there is just one thing that is absolutely required for any database provider — the ability to take regular backups of the DB automatically and the ability to restore the database from one of the backups.</p><p>‍All of this functionality is provided by AWS RDS along with an array of other capabilities like autoscaling of storage, multiple availability zones, etc. However we did not not really need this level of control over the DB for our simple SaaS product, not to mention the fact that RDS would cost us a minimum of 200$ a month with the lowest acceptable configuration.</p><p>‍Once again our saviour was Lightsail which provides managed Databases with a fixed storage at very cheap prices. Only MySQL and PostgreSQL are available though which was fine with us since I am quite comfortable with MySQL. We have currently provisioned one MySQL DB with 2 vCPUS, 4GB RAM and 120GB SSD and it costs us 60$ a month.</p><p>‍And as mentioned before Lightsail provides the basic capabilities of backups and restoration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/0*_bn7Jj35prYD34p2.png" /><figcaption>Database restoration from recent backup</figcaption></figure><p>The drawback here is that the DB will not scale automatically so your will have to make sure that your application does not use storage beyond what is available in the instance you select. We do this by regularly purging our Database of data that is older than X days and data that belongs to users who churned from our app more than X days ago and haven’t come back since.</p><p><strong>Caching instances</strong></p><p><strong>‍</strong>For our application we needed a Caching layer as well as the ability to queue up jobs that can be executed asynchronously. The seasoned folks here might have realised that the best tool to use for this is Redis and AWS has a service called ElastiCache which is Redis under the hood.</p><p>‍Once again this would be a very safe choice to make because it is completely managed and scalable. Our need was a Redis instance with at least 6GB of memory and 2vCPUs and if we went with ElastiCache our cost would roughly come out to be 112$ a month, not to mention the additional cost of running our async workers somewhere else.</p><p>‍I might sound like a broken record at this point but what we ended up doing was to provision a Lightsail instance with 2vCPUs and 8GB of memory for the cost of 40$ a month and installed an open source version of Redis on this instance. We also use the same instance to run our asynchronous workers which read from the Redis queue and execute jobs.</p><p>‍So what is the drawback? Well since it is not a managed service, you would have to monitor the Redis server yourself. There are many tools out there that help you do this and the one I would recommend is<a href="http://prometheus.io/"> prometheus.io</a>.</p><p>‍This means that you have to do a little bit of extra work to setup metrics collection from your Redis instance and use a grafana dashboard where you can view these metrics, but this extra work saves a lot of money in the long run and you get to look at a super cool dashboard like this one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7aNDYkPpjkAlv7mm.png" /><figcaption>Grafana dashboard for monitoring redis instance</figcaption></figure><p><strong>CDN</strong></p><p>Our application requires a javascript file to be loaded into the websites of our customers. This JS file gets a ton of traffic because this traffic scales according to how many visitors our customers get. Now this can be scary because it means we really had no idea how many requests the JS file might actually end up receiving so we hesitated to go with CloudFront which is the goto solution for a CDN on AWS.</p><p>‍So we ended up taking an entirely different approach for this. Our application is a Shopify app and during the process of building the application we created a Shopify store. Every Shopify store gets its own personal CDN where you can manually upload anything and it will be served over the Shopify CDN. So we minified and uploaded our JS file to the CDN of our Shopify store and now we serve 20000 Shopify stores using this method at zero cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w1otO2_XP5qFazAT.png" /><figcaption>Shopify CDN that is free of cost</figcaption></figure><p>There is a glaring drawback to this approach. The Shopify store CDN does not provide an API that you can use to programmatically upload files and it has to be done manually. Also unlike CloudFront, there is no option of invalidating a file once it is uploaded. So If you have to make updates to your file you would have to upload a new file and migrate all of your existing users to this new file.</p><p>‍This might sound like a big drawback, but it actually took me an hour to whip up a script that updates the JS file for all our existing 20000 stores to the updated JS file that I provide. So whenever I make a new release to this JS file, I simply upload a new file manually to the CDN, then take that file as the input and run this script and we re live! This approach works for us because we do not make too many releases to the JS file to begin with.</p><p><strong>Web server + load balancer</strong></p><p><strong>‍</strong>Every application requires the ability to route requests coming to their domain or subdomain to various applications running under the hood. The best way to do this is to use AWS ELB which can be used to automatically distribute incoming application traffic across multiple targets, such as Amazon EC2 instances, containers, IP addresses, and Lambda functions.</p><p>‍This sounds quite fancy, but all we needed for our product was 4 things‍</p><ul><li>Serving static files for our application dashboard</li><li>Distribute traffic among different Lightsail instances based on the path of the incoming URL</li><li>Load balance traffic that comes from our Merchants Shopify stores amongst N identical Lightsail instances.</li><li>Rate limiting of requests to prevent DDOS attacks.</li></ul><p>All of this can be done using NGINX which is a great piece of software and is quite robust even with the default settings that it comes with.</p><p>So we simply installed a stable version of NGINX on one of our existing Lightsail instances which was already being used to host one of our server applications. We also use<a href="http://amplify.nginx.com/"> amplify.nginx.com</a> for monitoring it. This setup is pretty much equivalent to using a managed service at zero cost.</p><p>‍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*itk-4dfAh2D1_FYN.png" /><figcaption>Amplify dashboard for monitoring health of the NGINX server</figcaption></figure><p>‍</p><p><strong>Summary</strong>‍</p><ul><li>Use lightsail instances (20$ per instance) instead of EC2 instances (37$ per instance)</li><li>Use a lightsail database (60$ per DB) instead of RDS (200$ per DB)</li><li>Use a self hosted redis server on a compute instance (40$) instead of ElastiCache (112$)</li><li>If feasible, use a free CDN (cost savings depends on traffic size)</li><li>Use a self hosted NGINX server (20$ fixed cost) instead of ELB (cost depends on traffic and usage)</li></ul><p><strong>Closing notes</strong></p><p>I would like to put emphasis on the fact that we are a micro-SaaS product that solves a small and specific use case and therefore this kind of AWS setup worked for us. This may not work for big organisations or products where the traffic is erratic.</p><p>This setup will also not work for folks who have a ton of stuff to do already and would prefer to use managed services and not take the additional headache of monitoring, maintaining and provisioning hardware resources on a regular basis because this has a time cost to it.</p><p>We are a team of 2 people with a product that is not computation heavy and has cloud requirements that are quite straightforward. We have been running this product for a little over 1 year with this AWS setup and so far we have not encountered any problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50e47230c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built a remote micro-saas business — a brief review of 2019]]></title>
            <link>https://medium.com/@sankalpjonna_89229/how-i-built-a-remote-micro-saas-business-a-brief-review-of-2019-3518bbd6e3af?source=rss-798c05e98697------2</link>
            <guid isPermaLink="false">https://medium.com/p/3518bbd6e3af</guid>
            <category><![CDATA[remote-business]]></category>
            <category><![CDATA[microsaas]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[annual-review]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[sankalp jonna]]></dc:creator>
            <pubDate>Thu, 02 Jan 2020 11:24:37 GMT</pubDate>
            <atom:updated>2020-01-02T11:24:37.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I built a remote micro-saas business — a brief review of 2019</h3><p>The end of the year is upon us and until now every time I came across someone else’s annual review I always wished that I had something to talk about as well, something significant that I had done in the year that was worth writing about and this year I actually do! 2019 was packed with so many experiences that it actually became necessary to write about it while it was still fresh in my mind.</p><p>My focus in this annual review would primarily be about my journey of building a software product from scratch, deploying it, serving &gt; 12000 users and ultimately monetising 10% of those users to reach the point of not having to work for somebody else to make a living.</p><p>I feel honoured to say that I have done this by building <a href="https://www.superlemon.xyz/">SuperLemon</a> together with my business partner Preetam. At the time of writing this post, SuperLemon was at $10,000 MRR and 300 reviews on the <a href="https://apps.shopify.com/">Shopify app store</a> with an average rating of 5.0 🌟. However saying that this year was only about building software would be an oversimplification and therefore I would like to break this review down in these 5 parts.</p><ul><li>Key Milestones</li><li>My first business partnership</li><li>Memorable moments</li><li>Interesting people that I met</li><li>Things to improve in 2020</li></ul><h3>Key Milestones</h3><p><strong>Learning how to code front-end</strong></p><p>I have been a backend developer for the past 5 years and while this was a very important skill, it was incomplete without knowing how to build the front-end part of a product. I needed to be able to build a full product by myself that I can package and sell without having to rely on a front-end engineer.</p><p>The problem with front-end technologies is that there are way too many of them, so I picked up the framework that would work best with my need to build a quick prototype — <a href="https://reactjs.org/">reactjs</a>. After spending a week reading tutorials and the official documentation I realised that we live in an age where the need to have complete knowledge over something has become obsolete.</p><p>There are tons of libraries and frameworks out there which I could simply plugin and get started without actually having to write much code myself. There are existing react components available for all sorts of boilerplate stuff that one would require like buttons, forms, sidebar navigation, etc.</p><p>The framework that I stuck to as a result of becoming a <a href="https://partners.shopify.com/">Shopify partner</a> was <a href="https://polaris.shopify.com/">polaris</a>. This allowed me to build a prototype for my product in a weeks time. I now have front-end development in my arsenal and it is a great feeling.</p><p><strong>Building a full stack product from scratch</strong></p><p>Now that I had the necessary skill set required to build a product entirely by myself, the next step was to build a product that solved a particular problem for a particular set of people and is production ready. Because I am only one person who just happened to learn front-end, it did not make sense to be too ambitious and build something that would serve millions of users.</p><p>This was when the term “micro-saas” really started to connect with me. The idea that you could build a tool that solved a particular problem for a particular niche of users seemed like the right fit and to that end building a plugin/extension for Shopify and putting it on the <a href="https://apps.shopify.com/">shopify app store</a> was a good a place to start.</p><p>At this juncture I should mention that I still do not have the ability to build a product entirely from scratch. This was because while I had the necessary skills to engineer a product, I did not have the skills to design one. Building a product starts with designing mockups and UI/UX flows, writing code is probably the last thing that takes place. I quickly realised that the last 5 years of backend development has conditioned me to be able to learn front-end in a week, but design was a whole different story. Fortunately I had an awesome business partner who specializes in exactly this, but more about that later.</p><p>In another weeks time with the help of my partner, I was able to whip up an MVP for <a href="https://apps.shopify.com/whatsapp-chat-button">this</a> product that helps e-commerce merchants increase their sales via WhatsApp.</p><p><strong>Distributing a product</strong></p><p>So now we have a micro-saas app that is ready to serve users. What do we do next? Why get users of course! Since the product is a Shopify app, it is pretty obvious that the users will come from the search bar on the Shopify app store, but how do we make sure that the app shows up when people search for something? By making sure we have the necessary keywords in our description, having a great copy and an easy onboarding flow.</p><p>Once this was done the next step was to get people to choose our product vs the competition. In order to do this we did something that some might consider unethical — we included most of the features that the competitors had and made the app FREE which forced the competitors to go into losses. You cannot build a business by being nice.</p><p>Making the app free got us a plethora of users to whom we provided exceptional customer service which lead to them writing 5 star reviews, so even though they were using the app for free, we derived ROI out of them by gently nudging them to write reviews which boosted our ranking and eventually got us to the #1 rank for certain keywords.</p><p>This was when something very interesting happened. One of our competitors ran a DDOS attack on our servers. At this point we were getting 5 reviews a day and users congratulating us for our good work but the fact that someone tried to screw us over made it evident that we were on the right track.</p><p><strong>Monetising a product</strong></p><p>While we were ecstatic that we had a product that is being used by people all over the globe, it was time to acknowledge the price we had to pay to get to this stage — the features that were being monetised by the competition are now free in our app, so we had to find new ways to monetise.</p><p>Fortunately this was not too difficult because as a result of making the app free we got a plethora of users who told us EXACTLY what they wanted and were willing to pay for. All we had to do was make a list of features requested by some of our power users and tally them to come up with the most frequently requested features.</p><p>This process was very enriching because we got to speak to people from all over the world in different languages (thank you Google translate!) and got to know their point of view and how e-commerce is done where they come from. This gave us priceless insights which we quickly utilized to come up with new features that people were willing to pay for. We even managed to get some users who were willing to beta test new features and report bugs before they propagated any further.</p><p>After gathering this information, we further shortened the list of requested features into something we could build in a week and launched our first paid plan for 3$ / mo and when we received the first paying subscription it gave me an unparalleled high which I never felt before. To be clear, the happiness that I felt had nothing to do with money, it was the fact that we built something so valuable that somebody from the other part of the globe was willing to take out money from their bank account and put it in ours. It is safe to say that this was the biggest milestone of all.</p><p><strong>Physical fitness</strong></p><p>I know what you’re thinking. What does physical fitness have to with building a software product? In my case there is a deep connection between the two. Here is how it started — I realised that I was 25 years old and really unfit and I needed to do something about it. This was back when I was working for <a href="https://greedygame.com/">GreedyGame</a> and had a 11–8 Job to go to. So the excuse I told myself to avoid working out was “I don’t have time” or rather I did not have the ability to choose my own timings since I could only work out before 11 am or after 8 pm.</p><p>So how do I choose my own time? By quitting my job and setting up an alternate source of income so that I gain the ability to work out at any time of the day I want. And If I were to achieve this, I would have absolutely no excuse to tell myself to avoid working out.</p><p>As you probably guessed, even after having this kind of freedom it is hard to find the motivation to work out, so I figured out a hack. I don’t like brushing my teeth everyday either, it is a very menial job, but I do it because it only takes 10 minutes and I can convince myself to take out 10 minutes a day for personal hygiene. Similarly, If I work out for only 15 minutes a day, it would be easy to convince myself to take out 15 minutes a day for fitness.</p><p>Now that I only had to endure only 15 minutes of pain every day, I was able to keep up this routine and slowly increase the time I spent on working out. I quickly realised that being consistent and doing this everyday had much more merit than working out for 2 hours a day for a week and then stop going to the gym for the rest of the year. This 15 minute a day routine enabled me to stay consistent throughout the year and I also slowly managed to increase this time to 35–45 minutes a day.</p><h3>My first business partnership</h3><p>If you want to start a business, there are two ways to go about it. You could conclude that nobody but yourself can align to your vision and start a very lonely journey until you become successful. If you are able to do this, you have my sincere respect. If not, you could meet enough people and wait long enough until you find somebody that aligns with your vision and has skills that complement yours.</p><p>I chose to do the latter and ended up partnering with <a href="https://in.linkedin.com/in/nathpreetam">Preetam Nath</a>. I worked at 4 different companies during the course of my career and I met him at one of those. After having enough conversations we decided that we had the same key metrics that we want to achieve in life, which include (1) Not having to work for someone else, (2) Building a remote business that doesn’t involve showing up to a workplace everyday, (3) Not having all our eggs in one basket (building multiple products).</p><p>Along with alignment of vision, we also had complementary skills. I was good at engineering products and Preetam was good at designing, marketing, and developing the business aspect of the product. We were a perfect combination of Brain and Brawn in the context of software products.</p><p>Any shred of doubt I had regarding this partnership was obliterated when Preetam was offered a huge raise at his previous workplace and he declined it in order to quit and start a business with me. From that moment onwards, we were unstoppable. We both quit our jobs around the same time and jumped head first into fulfilling our dreams.</p><h3>Memorable moments</h3><p><strong>Naming the company</strong></p><p>Trust me folks, naming your company is not as easy as it seems. Literally every single name that you can think of has already been thought of. A word of advice — when you land on a name for your company, do check the registry to see if it already exists before naming all your products and and buying a domain with that name!</p><p>As you probably guessed, we fell victim to this and ended up naming all our stuff even before registering a company, and we did not plan on making that mistake again, so we sat down and wrote down a list of fruits, colors, vegetables etc, and another list of adjectives and started matching them to come up with a name that is abstract enough. The name needed to be abstract because we did not really know what we were going to build yet.</p><p>We finally landing on the name <a href="https://www.superlemon.xyz/"><strong>SuperLemon</strong></a><strong>. </strong>It is abstract, has a nice ring to it and sounds refreshing. There is another reason why we came up with this name though which the woke audience will understand. *Wink Wink*.</p><p><strong>Making the first dollar</strong></p><p>Undoubtedly one of the most memorable moments was when the first payout hit our bank account. It was very empowering because it made us realise that we are fully capable of making a living on our own. It also gave rise to new possibilities that we haven’t thought of before like having the ability to hire somebody else and extract ourselves out of the day to day activities involved in running a business.</p><p><strong>First work vacation (workation)</strong></p><p>We have a constitution for SuperLemon that we kept amending throughout the year and one of the things in the constitution was to travel somewhere and work out of there at least once a year. The first place we chose to do this was Dharamshala, India where we spent around 15 days working out of the mountains.</p><p>This enabled us to stay fit since going anywhere in the mountains is a trek and basically a workout. We would work for 3–4 hours during the day and trek the rest of the time. We stayed in hostels and met some travellers with whom we had some stimulating conversations.</p><p>This was also where we met some awesome folks that had similar vision to ours and we somehow ended up congregating together, but more on that later.</p><p><strong>Hiring mishaps</strong></p><p>So far I have mostly highlighted the good stuff, but there were also bad things that happened in this journey. When you’re trying to build a remote business, hiring can be a real nightmare. There is no real way to evaluate if someone is good unless you work with them for a little bit and we quickly realised how hard it is to get good people who will do the work without being supervised.</p><p>We hired a couple of freelancers who basically sat idle for a month and we still had to pay for them. We also hired a full time guy who was a fresher and had the work ethic that we wanted, but did not have the experience which ended up in me hand holding him for everything and increase my work rather than decrease it. This was not the guy’s fault since he made it quite clear that he was still learning, but when you hire somebody who is going to work remotely, it is important to realise that you will not be able to guide them properly. Therefore the only thing you can do is hire experienced folks with good work ethic who will do the work without being supervised. Fortunately we ended up finding such people after a few months.</p><h3>Interesting people that I met</h3><p>It is safe to say that once you become an entrepreneur, you will find yourself in the company of other entrepreneurs. The people that we met during this journey helped us get to where we are and also serve as a constant reminder that we are not alone in this journey and we can reach out to these folks whenever we find ourselves in a problem.</p><p>The first truly interesting conversion we had was with Shashank, who was the founder of <a href="https://pushowl.com/">PushOwl</a>. He runs one of the biggest apps on Shopify and was a major reason why we got into Shopify app development in the first place. He taught us that the best way to succeed on Shopify was to provide exceptional customer service above all. He also helped us out with tech issues more than a few times. This motivated us to build a cartel of Shopify app developers via a WhatsApp group where can help each other out with common issues that might come up in this area.</p><p>The most interesting people that I met however were the founders of <a href="https://altcampus.io/">Altcampus</a> — Ankit and Prashant. We met these folks during our stay in Dharamshala. These are some truly exceptional people who are trying to change the education system in India by providing an alternative to a college campus. They run a software development bootcamp in the middle of the mountains in Dharamshala. Personally the thought of a couple of 25 year old kids building a college campus literally in the middle of nowhere was mind boggling for me.</p><p>What stood out the most was when I asked the co-founder Ankit what made them come to Dharamshala in the first place, he replied saying that back when he was working in a big city, he wanted to play football and he could not find a place to play so he ended up moving to the mountains where there was ample amount of space to play all he wanted!</p><p>This is the kind of clarity that I wish to have in life, where you are so committed to something that you stop whatever you are doing and move to the freakin mountains</p><h3>Things to improve in 2020</h3><p><strong>Write more</strong></p><p>I know full well that there are many more things about my journey that I can write about, but unfortunately those moments have already passed and they are no longer fresh in my mind. In order to avoid this in the future, I wish to write a post at least once every month. Even if nobody reads it, it would serve as a reminder for myself so that when I look back and read this a couple of years from now I can recollect all the awesome moments that took place.</p><p><strong>Better self supervision</strong></p><p>One of the downsides of running a remote business is that you will find yourself working from home on most days and this will result in the line between working and relaxing getting really blurry. One way to avoid this is to work out of coffee shops and simulate the environment of work. It is important to do this because it is very easy to slack off when you have nobody to answer to. Laziness can really creep up on you. I am currently writing this post from a coffee shop near my house where I hope to find myself on most days of the week so I can be more productive.</p><p><strong>Running multiple businesses</strong></p><p>As I mentioned earlier, I don’t want to put all my eggs in one basket. I devoted this entire year to a single product and while that resulted in really nailing it and getting it to a decent stage, there are many things that could go wrong which might result in this business shutting down. To avoid this risk I must learn to run multiple products at the same time while still working the same amount of hours that I do right now.</p><p><strong>Being a truly remote business</strong></p><p>Even though we managed to do this pretty well, Preetam and I still find ourselves the most productive when we work together in the same room. This cannot be the case if we want to run a business remotely. We have to be able to function efficiently even if each of us are on different time zones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3518bbd6e3af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An open source boilerplate for you next SaaS product, written in django]]></title>
            <link>https://medium.com/50k-tech/an-open-source-boilerplate-for-you-next-saas-product-written-in-django-423c90160800?source=rss-798c05e98697------2</link>
            <guid isPermaLink="false">https://medium.com/p/423c90160800</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[boilerplate-code]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[sankalp jonna]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 11:21:14 GMT</pubDate>
            <atom:updated>2019-03-26T08:29:16.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>An open source boilerplate for your next SaaS product, written in django</h3><p>While building our previous product SessionFox, we had to write a backend to handle common SaaS features such as users, subscriptions, plans, accounts, etc. Since we shut down, we decided to open source the SaaS backend for anyone to use. Fyi, you can find our other open source work <a href="https://50ktech.webflow.io/blog/an-open-source-boilerplate-for-you-next-saas-product-written-in-django">here</a>.</p><p>This article explains the database schema for any generic SaaS tool and the codebase for common APIs such as</p><ul><li><a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/views.py#L43">Login</a></li><li><a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/views.py#L62">Signup</a></li><li><a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/views.py#L67">Reset Password</a></li><li><a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/views.py#L48">Info about an invited user to pre-fill a signup form</a></li><li><a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/views.py#L96">Invite team member</a></li><li><a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/views.py#L84">Me</a></li></ul><p><a href="https://github.com/sankalpjonn/simple-saas"><strong>Link to Github repo</strong></a>‍</p><h3>Database models for SaaS</h3><p>To keep track of all the different registered businesses and the plans that those businesses are subscribed to, we need a schema that looks like this.</p><p>Each registered business might also have multiple users using that account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lhEXn1egG6EIpHno.png" /></figure><p>We originally used this schema to build SessionFox which is a mobile app session recording tool that we wanted to sell as a SaaS and therefore designed our schema in this way.</p><p>I will now explain how you can extend each of these models for whatever SaaS you are building.‍</p><h3>Plan</h3><p>To store information about the different kinds of plans that the SaaS offers. You might want to offer a free plan with limited capabilities and one or more paid plans with additional functionality.</p><p>Beyond this, there could be more fields in this model depending upon the use case. In the context of SessionFox, we offered plans based on number of session recordings and number of applications, so the additional fields in the Plan model for SessionFox were</p><ul><li>Max recordings</li><li>Max applications‍</li></ul><h3>Subscription</h3><p>Represents a plan subscription by a business. It will therefore contain a reference to business and plan. Can be used to check if there is an active subscription present for a given business and if so, which plan is the business subscribed to.</p><p>Can also be used to renew, upgrade or deactivate a subscription based on the plan duration expiry, special credits for a particular business, etc.</p><p>Start time and End time represent one cycle of a plan. For instance, if a plan has a duration of 15 days, and the subscription began on the 15th of August, start time would be 15th of August and end time would be 30th of August.</p><p>There will be a periodic task that retrieves all subscriptions where end time has passed and based on the subscribed plan, this task will decide whether to renew the plan, or deactivate the subscription. For running periodic tasks, we use <a href="https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679">timeloop.</a></p><p>In the context of SessionFox, when a new business signs up, a subscription is automatically created with a free plan, and since most of the new signups were beta users, we needed a way to upgrade those users to an unlimited plan. To do this, we created an entry in the plan model called <em>unlimited plan </em>where max_recordings and max_applications was a huge number and changed their corresponding subscription model entry to reference the unlimited plan.</p><p>You can also use this model to store information that resets when a new plan cycle starts. For instance, in SessionFox once the business reached the max recording limit, we had to prevent any further recordings from that business. So we kept a field called current_recording_count in this model. This field is incremented whenever a new session recording is created and when it reaches the max limit of the corresponding plan, the recording API will return a response appropriately.</p><p>Since we were already running a periodic task to update the start time and end time of the subscription, we used the same task to reset the current_recording_count, so that for the next plan cycle, it starts from zero.‍</p><h3>Business</h3><p>Represents a subscriber of the SaaS tool.</p><p>Any additional fields that is specific to a business can be put in this model. For SessionFox, in order for the client to call the APIs, an API_KEY would be issued and this field can be set in the business model.‍</p><h3>BusinessTeamMember</h3><p>Now that we have all models required to track SaaS subscriptions for a business, we need a model to keep track of all the users that are accessing the product. These users could be</p><ul><li>Multiple team members from the same business</li><li>Bots</li></ul><p>Regardless of whether the user is a bot or a team member from the business, we need a way to define what permissions a particular user will posses. In the context of SessionFox, API calls need to be made to the server by the SDK as well as the dashboard. In order to do this, the SDK would be given an access token, but this access token should not posses permissions to access the dashboard APIs.</p><p>Restricting API access using permissions is something that is made quite trivial using django-rest-framework, which I will be talking about in detail in the later stages of this article.</p><p>There is also an activation_key in this model. This will come in handy when another team member is invited to use the account.</p><p>The invitee must be sent a link containing the activation key and opening this link must result in a redirection to the signup form which must be pre-filled with some of the existing information of the invitee including the business id by calling an API with the activation_key.</p><h3>Django make things easier, here’s how</h3><ul><li>Combined with django-rest-framework, API creation becomes very trivial</li><li>Easy to manage authentication and permissions using auth token.</li></ul><p>The database models mentioned above can be translated into django models like <a href="https://github.com/sankalpjonn/simple-saas/blob/daaae14f0fce74f7fcf961d2eacea729c9fcb99b/saas/models.py">this</a>.‍</p><h3>Managing users and permission</h3><p>The BusinessTeamMember model represents a single user. However there is no need to explicitly have fields for username and password. Instead we can use <a href="https://docs.djangoproject.com/en/2.1/topics/auth/default/#user-objects">django users</a>. This Model provided by django abstracts the user authentication system and it automatically stores passwords as hashes. The user can also be activated or deactivated by using the is_active field. Hence the BusinessTeamMember model can simply contain a foreign key to the django user model.</p><p>Using django rest framework, every django user created in the system can be assigned an access token, and if this access token is present in the header of an API call, django-rest-framework automatically queries the user to which this token belongs and attaches it to the API request. You can find out more about django-rest-frameworks authentication system <a href="https://www.django-rest-framework.org/api-guide/authentication/">here</a></p><p>Now we need a mechanism to have different access control on different APIs. This is done using django-rest-frameworks <a href="https://www.django-rest-framework.org/api-guide/permissions/">permissions</a><strong>.</strong> An API can be defined as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aff154e494356cebfd7f68a1741f9636/href">https://medium.com/media/aff154e494356cebfd7f68a1741f9636/href</a></iframe><p>For SessionFox, we needed a way for our staff to login to any of the business’ account for Support/QA purposes. We also needed a user that can make API calls from the SDK. To do this, for every signup instead of creating a single BusinessTeamMember, we create 3 as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ed43e2e3a068ec21ac3d4a1875b8e87/href">https://medium.com/media/6ed43e2e3a068ec21ac3d4a1875b8e87/href</a></iframe><p>The auth token of the sdk_user is what we give out to a business as their API_KEY once they finish the signup process. They will then include this API_KEY in the manifest file of their Android app. And since we will restrict the permissions of an SDK user, even if this API_KEY gets leaked, no real damage can be done.</p><p>If a user needs to invite other users to use the account, we can simply expose an API that creates a new BusinessTeamMember with an activation key that is then mailed to the invitees. Once the invitee confirms activation from his mailbox, the is_active field in the user model can be toggled and a new user in the system is created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dce3d4c161c1fecfde94f77f5126a5c/href">https://medium.com/media/4dce3d4c161c1fecfde94f77f5126a5c/href</a></iframe><p>If the invitee clicks on the activation link, he can be redirected to the signup form where the email address is pre-filled and the activation key is kept hidden. In order to pre-fill the form, an API can be called with the activation_key in the query params as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/896b9c7a8f4870775486acb3d2725c72/href">https://medium.com/media/896b9c7a8f4870775486acb3d2725c72/href</a></iframe><p>When signup API is called, instead of following the regular signup flow, since this user already exists and only needs to be activated and have the password changed, you can do the following -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65f711cc8564baa9198c0ea97b47d422/href">https://medium.com/media/65f711cc8564baa9198c0ea97b47d422/href</a></iframe><h3>Business logic inside serializers</h3><p>Django-rest-framework enables you to</p><ul><li>Validate request data</li><li>Run business logic for the API</li><li>Serialize response</li></ul><p>And the best part is that all the above three operations can be encapsulated inside a serializer class. If the API inherits CreateAPIView, first validate() method inside the serializer is called to check if the incoming request is valid or not, after this create() method is called with the validated data as the input. Therefore all business logic can be kept inside create(). And any additional validations that need to be done on the request can be inside validate().</p><p>If a validate() returns a validation error, a 400 response code is automatically sent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66f3ec91757be85b9317888648e0d607/href">https://medium.com/media/66f3ec91757be85b9317888648e0d607/href</a></iframe><h3>Subscribe for more</h3><p>If you’ve read until this point, I thank you for your time and patience. Subscribe to our newsletter down below and we will keep you posted on our adventures!</p><figure><a href="https://tech.us20.list-manage.com/subscribe?u=b0842bd84c8610dcbfba24a4a&amp;id=6c2663d486"><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Yp4ioJReoZrH5lrkjLe2uQ.png" /></a><figcaption>Read about our struggles and hardships, new launches, successes and failures, business learnings, open source code that we publish, and everything else in between from the team at 50k.tech as we march towards our goal of earning $50k in MRR.</figcaption></figure><p>And if you have any feedback or thoughts, you can reach us <a href="https://twitter.com/hipreetam93">@s</a>ankalpjonna or <a href="https://twitter.com/sankalpjonna">@</a><a href="https://twitter.com/hipreetam93">hipreetam93</a>. We would love to chat :)</p><p><em>Originally published at </em><a href="https://www.50k.tech/blog/an-open-source-boilerplate-for-you-next-saas-product-written-in-django"><em>www.50k.tech/blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=423c90160800" width="1" height="1" alt=""><hr><p><a href="https://medium.com/50k-tech/an-open-source-boilerplate-for-you-next-saas-product-written-in-django-423c90160800">An open source boilerplate for you next SaaS product, written in django</a> was originally published in <a href="https://medium.com/50k-tech">50k.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An elegant way to run periodic tasks in python]]></title>
            <link>https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679?source=rss-798c05e98697------2</link>
            <guid isPermaLink="false">https://medium.com/p/61b7c477b679</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[sankalp jonna]]></dc:creator>
            <pubDate>Tue, 30 Oct 2018 07:29:38 GMT</pubDate>
            <atom:updated>2018-10-30T07:43:26.216Z</atom:updated>
            <content:encoded><![CDATA[<p><em>At GreedyGame, we try to help Game Developers monetize without hampering the gameplay experience of the Gamer. We work towards creating a better ad ecosystem by bringing native ads to mobile games and creating Ads people ❤</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*aXicALITNE0zM_hn.jpg" /></figure><p>Periodic tasks are tasks which are executed at specified time intervals, again and again, with minimal human intervention. Every engineer would have used it in one way or the other, to schedule periodic database backups, enriching data for your Machine Learning algorithm, polling an API, daily marketing emails, etc.</p><p>I was working on a module which needed me to keep some entries in a database table for a certain period of time post which the entries should get deleted automatically. In order to do this I wanted to go with the following approach:</p><ol><li>Include an <strong>expire_at</strong> column in the table</li><li>Run a periodic task that deletes all entries from the table where <strong>expire_at &lt; current time</strong></li></ol><p>The most common approach is to use a cron job, however using a cron will have a dependency on an external process that is not part of your code base which will have to be managed separately. I wanted something that could be accessed within my package.</p><p>With python, there are several ways of creating and executing a periodic task. Some common ways are:</p><ol><li><a href="http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html"><strong>Celery beat</strong></a></li><li><strong>Using</strong> <strong>time.sleep</strong></li><li><strong>Using</strong> <strong>threading.Timer</strong></li><li><strong>Using threading.Event</strong></li></ol><h4>1. Celery beat</h4><p>Using celery beat, tasks can be started at regular intervals which would be picked up by available workers in a cluster.<br>This is a heavy framework with such level of complexity which is not required for most types of use cases. For my specific use case I needed a lightweight utility.</p><h4>2. Using time.sleep</h4><p>One could run a simple loop with whatever duration you want in <strong>time.sleep</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a545889638e2b2a973a2ecbbb903d7/href">https://medium.com/media/72a545889638e2b2a973a2ecbbb903d7/href</a></iframe><p>With this approach, if the program is killed in between, the function <strong>foo()</strong> would be killed abruptly. Also if you want to run multiple tasks at different periods you would have to do that separately in another script.</p><h4>3. Using a Timer</h4><p>A periodic task could also be implemented using the <strong>Timer</strong> on a thread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11baf509bdb1d902c37f44c8b7c0f268/href">https://medium.com/media/11baf509bdb1d902c37f44c8b7c0f268/href</a></iframe><p>This approach has the same problems that exists in the time.sleep approach. Instead we can use the <strong>threading.Event</strong> module.</p><h4>4. Using threading.Event</h4><p>threading.Event module has a flag that can be set or reset at any point of time using set() and clear(). It also has a wait() method which blocks until the flag is set. This functionality can be used to created a periodic task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0b69e1077190f123e2fa6f92a94100e/href">https://medium.com/media/c0b69e1077190f123e2fa6f92a94100e/href</a></iframe><h3>Need for a lightweight approach</h3><p>In all the previous methods, there is no way to guarantee a graceful shutdown of tasks, in case the program is killed or has ended abruptly.</p><p>When a program has to be shut down gracefully, it is advised to do it via a soft kill which sends a SIGKILL signal to the program. The program can then intercept this signal and run some cleanup code before exiting. It could also intercept a SIGINT signal which is sent when you stop running a program via the ctrl+c command.</p><p>In python, this can be done using the signal module which can intercept the above signals. But the tasks must run in separate threads so that the main thread can be used to catch the signals and run the cleanup code. Please refer to this code snippet for context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a448205039ac7eca7031457fbd9e1c/href">https://medium.com/media/b1a448205039ac7eca7031457fbd9e1c/href</a></iframe><p>Hence I wanted to design a library that had the following capabilities.</p><ol><li>Run multiple periodic tasks at different intervals.</li><li>When a program is killed, all tasks that are currently running must be completed before the program exits.</li><li>The library should be simple to implement and use. ( I went with a decorator pattern, which is a good way to attach additional responsibilities to an object dynamically. This is a better alternative than to extend functionality using a subclass.)</li></ol><h3>Introducing timeloop</h3><p><a href="http://github.com/sankalpjonn/timeloop"><strong>timeloop</strong></a> is a library which can be used to run multiple period tasks. It uses a decorator pattern and can be integrated easily in any existing code base, or used as a stand alone program.</p><p>All jobs declared by the decorator will run as separate threads.</p><h4>Installation</h4><pre>pip install timeloop</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddbf2326c093dd0764c8a0452c69ef2a/href">https://medium.com/media/ddbf2326c093dd0764c8a0452c69ef2a/href</a></iframe><p>If this program is killed or interrupted, it will wait for all the jobs that are currently running before exiting.</p><p><a href="https://github.com/sankalpjonn/timeloop">sankalpjonn/timeloop</a></p><p>Happy looping!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61b7c477b679" width="1" height="1" alt=""><hr><p><a href="https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679">An elegant way to run periodic tasks in python</a> was originally published in <a href="https://medium.com/greedygame-engineering">GreedyGame Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>