<?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 Ankit Gupta on Medium]]></title>
        <description><![CDATA[Stories by Ankit Gupta on Medium]]></description>
        <link>https://medium.com/@mailtoankitgupta?source=rss-46f568b9f95c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hyz6BgtDGykajU4BXGNp1Q.jpeg</url>
            <title>Stories by Ankit Gupta on Medium</title>
            <link>https://medium.com/@mailtoankitgupta?source=rss-46f568b9f95c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:56:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mailtoankitgupta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Add Comment Sentiment Analysis and Summarization Techniques Using Pre-Trained Models]]></title>
            <link>https://medium.com/@mailtoankitgupta/how-to-add-comment-sentiment-analysis-and-summarization-techniques-using-pre-trained-models-8aa729a0d71f?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa729a0d71f</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 03:38:27 GMT</pubDate>
            <atom:updated>2025-01-17T03:51:25.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sentiment Analysis and Summarization Using Pre-Trained Models</h3><h3>Introduction</h3><p>In the era of big data, businesses are inundated with customer feedback across various platforms — e-commerce reviews, social media, surveys, and more. While this data holds valuable insights, extracting meaningful information manually can be time-consuming and inefficient. Sentiment analysis and summarization techniques powered by pre-trained models are game-changers for tackling this challenge.</p><p>This article delves into how you can implement these techniques using leading pre-trained models, such as ChatGPT, Hugging Face Transformers, and Google’s Gemini. We’ll cover their applications, working solutions, key challenges, and how to make informed decisions when integrating these models into your workflows.</p><h3>Applications of Sentiment Analysis and Summarization</h3><h3>1. E-commerce Reviews</h3><ul><li>Analyze customer sentiment to identify patterns and trends.</li><li>Summarize product reviews into digestible highlights for prospective buyers.</li></ul><h3>2. Customer Support</h3><ul><li>Prioritize support tickets based on sentiment scores.</li><li>Summarize detailed issue descriptions for quicker resolution.</li></ul><h3>3. Social Media Monitoring</h3><ul><li>Track brand sentiment by analyzing social media comments and posts.</li><li>Summarize trending topics or viral content for quick strategic decisions.</li></ul><h3>4. Survey Feedback</h3><ul><li>Analyze sentiment across open-ended survey responses.</li><li>Generate summaries for comprehensive reports.</li></ul><h3>Working Solutions Using Pre-Trained Models</h3><h3>1. ChatGPT</h3><h4>Overview</h4><p>ChatGPT, developed by OpenAI, is a conversational AI model excelling in language comprehension and generation. It is versatile for both sentiment analysis and summarization tasks with minimal configuration.</p><h4>Implementation</h4><p><strong>Sentiment Analysis Example</strong></p><pre>import openai<br>openai.api_key = &quot;your-api-key&quot;<br>def analyze_sentiment(feedback):<br>    prompt = f&quot;Analyze the sentiment of this review:\n\n{feedback}\n\nProvide a sentiment score (Positive, Negative, Neutral) and reasoning.&quot;<br>    response = openai.Completion.create(<br>        engine=&quot;text-davinci-003&quot;,<br>        prompt=prompt,<br>        max_tokens=50<br>    )<br>    return response.choices[0].text.strip()<br>feedback = &quot;The product is great, but the delivery was delayed.&quot;<br>print(analyze_sentiment(feedback))</pre><p><strong>Summarization Example</strong></p><pre>def summarize_reviews(reviews):<br>    prompt = f&quot;Summarize these reviews into key points:\n\n{reviews}&quot;<br>    response = openai.Completion.create(<br>        engine=&quot;text-davinci-003&quot;,<br>        prompt=prompt,<br>        max_tokens=100<br>    )<br>    return response.choices[0].text.strip()<br><br>reviews = &quot;&quot;&quot;<br>1. Excellent product quality.<br>2. Delivery was slower than expected.<br>3. Good customer service overall.<br>&quot;&quot;&quot;<br>print(summarize_reviews(reviews))</pre><p><strong>Note</strong>: You can replace the model with the latest gpt-4o or gpt-4o-miniand tweak the parameters for temperature for better accuracy. Not expanding on these for brevity of the post.</p><h3>2. Hugging Face Transformers</h3><h4>Overview</h4><p>Hugging Face offers an extensive library of NLP models like BERT, T5, and RoBERTa, which are highly adaptable for a variety of text processing tasks.</p><h4>Implementation</h4><p><strong>Sentiment Analysis Example</strong></p><pre>from transformers import pipeline<br><br>sentiment_analyzer = pipeline(&quot;sentiment-analysis&quot;)<br>feedback = &quot;Great product, but the packaging was damaged.&quot;<br>result = sentiment_analyzer(feedback)<br>print(result)</pre><p><strong>Summarization Example</strong></p><pre>summarizer = pipeline(&quot;summarization&quot;)<br>reviews = &quot;&quot;&quot;<br>The product is affordable and well-built. Delivery was prompt. However, the instructions were unclear.<br>&quot;&quot;&quot;<br>summary = summarizer(reviews, max_length=50, min_length=25, do_sample=False)<br>print(summary[0][&#39;summary_text&#39;])</pre><h3>3. Google Gemini</h3><h4>Overview</h4><p>Gemini, Google’s advanced AI model, integrates text processing, reasoning, and multimodal capabilities, making it a robust choice for enterprise-grade applications.</p><h4>Implementation</h4><p><strong>Sentiment Analysis Example</strong></p><pre>from google.cloud import language_v1<br><br>client = language_v1.LanguageServiceClient()<br>def analyze_sentiment(text):<br>    document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)<br>    sentiment = client.analyze_sentiment(request={&quot;document&quot;: document}).document_sentiment<br>    return {&quot;score&quot;: sentiment.score, &quot;magnitude&quot;: sentiment.magnitude}<br>feedback = &quot;User-friendly app, but crashes occasionally.&quot;<br>print(analyze_sentiment(feedback))</pre><h3>Key Challenges</h3><p><strong>Scalability: </strong>Processing large datasets can be resource-intensive and expensive.</p><p>API calls might limit throughput for high-volume applications.</p><p><strong>Accuracy: </strong>Pre-trained models may struggle with domain-specific language or highly technical feedback.</p><p>Handling localization challenges, such as comments in multiple languages or regional dialects, may require additional fine-tuning or multilingual models.</p><p>Emojis and informal text (e.g., “The service was 😍 but the wait was 😞”) often skew sentiment analysis, demanding additional preprocessing to interpret correctly.</p><p><strong>Cost Considerations: </strong>API-based models like ChatGPT and Gemini can be expensive for large-scale usage.</p><p>Additional costs for storage, bandwidth, and cloud resources may arise.</p><p><strong>Data Privacy and Security: </strong>Sharing sensitive data with third-party APIs poses privacy risks and compliance challenges.</p><p>Ensuring data anonymization and secure handling adds operational overhead.</p><p><strong>Latency: </strong>Real-time applications may face delays due to API response times.</p><p>Optimizing for low latency while maintaining high accuracy is a balancing act.</p><h3>Conclusion</h3><p>Sentiment analysis and summarization are invaluable tools for extracting insights from unstructured text data. With pre-trained models like ChatGPT, Hugging Face Transformers, and Google Gemini, implementing these techniques has become more accessible and efficient.</p><p>While each model has its strengths, the choice depends on your specific requirements:</p><ul><li><strong>ChatGPT:</strong> Ideal for rapid prototyping and versatile text tasks.</li><li><strong>Hugging Face:</strong> Best for customizable and open-source solutions.</li><li><strong>Google Gemini:</strong> Suitable for enterprise-grade applications with robust integration capabilities.</li></ul><p>Addressing scalability, accuracy, and cost is essential to ensure successful deployment. By leveraging these advanced tools, businesses can unlock the full potential of customer feedback, driving innovation and growth in a data-driven world.</p><p><em>This post was created with the help of AI writing tools, carefully reviewed, and edited by the human author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa729a0d71f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using JIRA to improve productivity in remote teams]]></title>
            <link>https://medium.com/@mailtoankitgupta/using-jira-to-improve-productivity-in-remote-teams-d138fd52f4c0?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d138fd52f4c0</guid>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[employee-timetracking]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 01:19:11 GMT</pubDate>
            <atom:updated>2024-11-12T01:19:11.226Z</atom:updated>
            <content:encoded><![CDATA[<p>Productivity plays a vital role in enhancing a team’s efficiency. It is especially important for remote teams, where you, as a lead/project manager, cannot directly watch over what your team is working on.</p><p>We have all used project management tools and I found their task-based time tracking extremely useful in setting up accountability within the team.</p><p>Here is a quick look into how to achieve this with JIRA-</p><ol><li>Original Estimates — The assignee fills in the original estimates (preferably in hours) that describe the time it would take to complete the task including development &amp; testing. It is fine if it is a ballpark in case the task is unclear.</li><li>Remaining Estimates — The assignee updates the remaining estimates and logs the work done (in hours) typically before standups.</li></ol><p><strong>Note</strong>: Time tracking may not be automatically enabled in the fields in an issue in JIRA. You can add it using the Configure Fields icon for any issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQbIvqculE0MuRYTg-w51A.png" /></figure><p><strong>Once the task closes, you can compare the original and actual time taken and have retrospectives on what were the reasons for the delay if any, and on what to do better.</strong></p><p><strong>Note</strong>: This, however, doesn’t mean that the owner can fill in superfluous estimates and then beat it. That is the work of the team lead/project manager to make sure the estimates are reasonable.</p><h4>Accountability &amp; Anamoly tracking</h4><p>There is one side benefit to this tracking, you can use it over a weekly sprint to understand how much effort a person devoted to his set of tasks and check for anomalies like someone putting in fewer hours across his tasks in the sprint.</p><p>So, instead of setting up expensive employee time-tracking tools like TimeDoctor, to gauge employee productivity which IMO exhibits a lack of trust, you can use JIRA or any other project management tools to achieve the same result. Productivity.</p><p>The goal of the 2 kinds of tools is quite different, one tries to tell how many hours did one actually work. The other tries to tell how well you completed a particular task — did you meet your estimates or did you overshoot? Strive for the latter.</p><p>Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d138fd52f4c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a scraper for Instagram]]></title>
            <link>https://medium.com/@mailtoankitgupta/scraping-instagram-using-apify-e95f68aeb354?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e95f68aeb354</guid>
            <category><![CDATA[crawling]]></category>
            <category><![CDATA[apify]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[crawler]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 02:42:01 GMT</pubDate>
            <atom:updated>2024-11-05T02:40:32.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n6IH4Xu9zzG8buDZ" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I will be talking about how to scrape Instagram profile data using an open source crawler <a href="https://crawlee.dev/"><em>crawlee</em></a> and run it on <a href="https://apify.com/">Apify</a>.</p><p>crawlee — Is an open source library that provides a way to easily crawl hundreds and thousands of pages.</p><p>apify — Is a platform to run your crawler on. crawlee library is provided by apify itself and can be used to write the crawlers</p><p>apify is not a pre-requisite to crawl, but if you want a managed way to run your crawlers you need to run them either on an AWS lambda (which can be a bit of work) or you can host it on Apify. For my PoC purposes I ran it on Apify for ease.</p><h4>Scraping Public Content</h4><p>Below we will be talking about how to crawl the public profile data of any profile — name, image, bio, posts count, followers count, following count</p><p>The crawler I wrote utilizes the <a href="http://playwright.dev/">Playwright</a> automation for rendering the instagram page on the browser and then parsing the html content to extract the information.</p><p><em>crawlee</em> has a separate interface to use Playwright based crawler.</p><p>main.js</p><pre>// For more information, see https://docs.apify.com/sdk/js<br>import { Actor } from &#39;apify&#39;;<br>// For more information, see https://crawlee.dev<br>import { PlaywrightCrawler } from &#39;crawlee&#39;;<br>// this is ESM project, and as such, it requires you to specify extensions in your relative imports<br>// read more about this here: https://nodejs.org/docs/latest-v18.x/api/esm.html#mandatory-file-extensions<br>import { router } from &#39;./routes.js&#39;;<br>import cookies from &#39;./cookies.json&#39; with { type: &quot;json&quot; };<br><br>// Initialize the Apify SDK<br>await Actor.init();<br><br>const usernames = [<br>  &quot;humansofny&quot;,<br>];<br>let profileUrls = usernames.map(<br>  (username) =&gt; `https://www.instagram.com/${username}/`<br>);<br><br>const startUrls = await Actor.getInput() ?? [];<br><br>const proxyConfiguration = await Actor.createProxyConfiguration();<br><br>const crawler = new PlaywrightCrawler({<br>    // proxyConfiguration,<br>    requestHandler: router,<br>    preNavigationHooks: [<br>      async (crawlingContext, gotoOptions) =&gt; {<br>          crawlingContext.page.context().addCookies(cookies)<br>      },<br>  ],<br>});<br><br>await crawler.run(startUrls); // provides the crawler the list of starting urls<br><br>// Exit successfully<br>await Actor.exit();</pre><p>This is mostly trying to initialize the crawler passing in the routes that we plan to handle.<br>We can skip the cookies as I will talk about them later.</p><p>routes.js</p><pre>import { createPlaywrightRouter } from &quot;crawlee&quot;;<br><br>export const router = createPlaywrightRouter();<br><br>const getFollowersCount = async ({ page }) =&gt; {<br>  const followers = await page.getByText(/[0-9,.mMkK]+ followers/);<br>  if (!followers) {<br>    return { followersCount: 0, followers };<br>  }<br>  const textContent = await followers.textContent();<br>  const followersCount = textContent.split(&quot; &quot;)[0];<br>  return { followersCount, followers };<br>};<br><br>const getFollowsCount = async ({ page }) =&gt; {<br>  const follows = await page.getByText(/[0-9,.mMkK]+ following/);<br>  if (!follows) {<br>    return { followsCount: 0, follows };<br>  }<br>  const textContent = await follows.textContent();<br>  const followsCount = textContent.split(&quot; &quot;)[0];<br>  return { followsCount, follows };<br>};<br><br>const getPostsCount = async ({ page }) =&gt; {<br>  const posts = await page.getByText(/[0-9,.mMkK]+ post/);<br>  if (!posts) {<br>    return { postsCount: 0, posts };<br>  }<br>  const textContent = await posts.textContent();<br>  const postsCount = textContent.split(&quot; &quot;)[0];<br>  return { postsCount, posts };<br>};<br><br>const getProfilePicture = async ({ page, username }) =&gt; {<br>  const altText = `${username}&#39;s profile picture`<br>  const imageSrc = await page.getAttribute(`img[alt=&quot;${altText}&quot;]`, &#39;src&#39;);<br>  return imageSrc;<br>}<br><br>const getParentNode = async (node, level) =&gt; {<br>  if (level === 0) {<br>    return node;<br>  }<br>  if (!node) {<br>    return null;<br>  }<br>  const parentNode = await node.locator(&quot;..&quot;);<br>  return await getParentNode(parentNode, level - 1);<br>};<br><br>const getBio = async ({ page, contentNode }) =&gt; {<br>  const data = {};<br>  const contentParentNode = await getParentNode(contentNode, 3);<br>  if (contentParentNode) {<br>    const bioParentNode = contentParentNode.locator(&quot;+ *&quot;);<br>    if (bioParentNode) {<br>      const firstParent = bioParentNode.locator(&quot;&gt; *&quot;).nth(0);<br>      const children = firstParent.locator(&quot;&gt; *&quot;);<br>      const childrenCount = await children.count();<br>      data.fullName = await children.nth(0).textContent();<br>      data.isBusinessAccount = false;<br>      if (childrenCount &gt; 1) {<br>        // iterate from 1 to len<br>        for (let i = 1; i &lt; childrenCount; i++) {<br>          const child = children.nth(i);<br>          const textContent = await child.textContent();<br>          console.log(`Child ${i}: ${textContent}`);<br>          if (textContent.startsWith(&quot;Brand&quot;)) {<br>            data.isBusinessAccount = true;<br>          } else if (textContent.startsWith(&quot;Link&quot;)) {<br>            data.link = textContent.split(&quot;Link icon&quot;)[1];<br>          } else if (textContent.startsWith(&quot;Threads&quot;)) {<br>            data.threads = textContent.split(&quot;Threads&quot;)[1];<br>          } else {<br>            // TODO: handle &quot;more&quot; in the bio<br>            data.bio = textContent;<br>          }<br>        }<br>      }<br>    }<br>  }<br>  return data;<br>};<br><br>const profileHandler = async({ request, page, log, pushData}) =&gt; {<br>  log.info(`Processing profile: ${request.loadedUrl}`);<br>  log.info(`Title is ${await page.title()}`);<br><br>  const username = request.loadedUrl<br>    .split(&quot;/&quot;)<br>    .filter((x) =&gt; x.length &gt; 0)<br>    .pop();<br><br>  const { postsCount, posts: postsNode } = await getPostsCount({ page });<br>  const { followersCount } = await getFollowersCount({ page });<br>  const { followsCount } = await getFollowsCount({ page });<br>  const bio = await getBio({ page, contentNode: postsNode });<br><br>  const profilePicture = await getProfilePicture({ page, username });<br><br>  await pushData({<br>    url: request.loadedUrl,<br>    username,<br>    profilePicture,<br>    postsCount,<br>    followersCount,<br>    followsCount,<br>    ...bio,<br>  });<br>};<br><br>router.addDefaultHandler(profileHandler);</pre><p>This is the main meat of the scraping on the instagram returned web page.<br>We utilize the page.getByText for most of the fields — posts count, follower/following count.</p><p>For bio — we need to find an anchor element on the page which we can use to navigate to the bio div. We use the posts element used before to find the bio element by traversing to the parent section and then finding the next sibling.</p><p>There can be other ways but we do not intentionally scrape using the div IDs or class names in general, as those can change over time (as the classes are dynamically generated during build). This makes the crawler code fragile, requiring frequent updation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBRJAl-dgbWgkUgf2cLGcQ.png" /></figure><p>Finally, we collate all the fields and return them which the library neatly records it as a dataset stored as a json file. Output like below:</p><pre>{<br> &quot;url&quot;: &quot;https://www.instagram.com/humansofny/&quot;,<br> &quot;username&quot;: &quot;humansofny&quot;,<br> &quot;profilePicture&quot;: &quot;https://instagram.fdel3-2.fna.fbcdn.net/v/t51.2885-19/118982623_353024589077161_7490638455124782637_n.jpg?stp=dst-jpg_s150x150&amp;_nc_ht=instagram.fdel3-2.fna.fbcdn.net&amp;_nc_cat=101&amp;_nc_ohc=WEggU4_7AmgQ7kNvgHJu938&amp;_nc_gid=b0ef29be44094127913bc253c1146e7a&amp;edm=APHcPcMBAAAA&amp;ccb=7-5&amp;oh=00_AYBtQsMjxAY7AuYrEhk5ky33s67Rk2z4BUr3BLx5WjiunA&amp;oe=66E722A8&amp;_nc_sid=bef7bc&quot;,<br> &quot;postsCount&quot;: &quot;5,713&quot;,<br> &quot;followersCount&quot;: &quot;12.8M&quot;,<br> &quot;followsCount&quot;: &quot;413&quot;,<br> &quot;fullName&quot;: &quot;Humans of New York&quot;,<br> &quot;isBusinessAccount&quot;: false,<br> &quot;threads&quot;: &quot;humansofny&quot;,<br> &quot;bio&quot;: &quot;New York City, one story at a time. Created by Brandon Stanton. Humans of New York is audience supported; please... more&quot;,<br> &quot;link&quot;: &quot;bit.ly/HONYPatreon&quot;<br>}</pre><h4>Avoid Getting Banned</h4><p>If you crawl a lot of pages then Instagram can ban your IP, in which case your crawlers will start failing.</p><p>In order to avoid this you need to use proxies which simulate traffic coming from different places, this making Instagram believe that it is not being hit by bots.</p><p>Proxies are of 2 types:</p><ol><li>Residential proxies — These are expensive as they can simulate almost real traffic to Instagram as done by a real user.</li><li>Data center proxies — These are the cheapest form of proxies but they have a higher failure rate as its easier for Instagram to detect them.</li></ol><p><em>crawlee</em> has a way to specify the proxy configuration of the proxy urls that you have bought. If you are running on Apify this will be handled for you.</p><p>In the main.js you can include the proxyConfiguration which will take care of that for you.</p><pre>const proxyConfiguration = await Actor.createProxyConfiguration();<br><br>const crawler = new PlaywrightCrawler({<br>    proxyConfiguration,<br>    requestHandler: router,<br>    preNavigationHooks: [<br>      async (crawlingContext, gotoOptions) =&gt; {<br>          crawlingContext.page.context().addCookies(cookies)<br>      },<br>  ],<br>});</pre><p>That’s it!</p><p>In the next post I will talk about how to access logged in content, for example if you want to crawl the audiences of a particular profile, which are not available if you are logged out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e95f68aeb354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tech Co-Founder Dilemma: Are You Ready for the Challenge?]]></title>
            <link>https://medium.com/@mailtoankitgupta/the-tech-co-founder-dilemma-are-you-ready-for-the-challenge-e3d13c5694e2?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3d13c5694e2</guid>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[cto]]></category>
            <category><![CDATA[cofounders]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 01:44:10 GMT</pubDate>
            <atom:updated>2024-06-18T01:44:10.697Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re thriving at your desk job, bonding with colleagues over technical debates, and getting excited about the latest innovations. But then, it hits you: solving technical problems isn’t enough. You crave the thrill of addressing real customer issues, and you’ve got ideas swirling in your head.</p><p>So, when you meet someone searching for a tech visionary to build the next Apple (hello, Steve Jobs inspiration!), you start to wonder — should you dive in and explore this new opportunity?</p><p>Having been through countless co-founder discussions, I know the drill. My first foray was classic: a coffee shop chat, a business plan sketched on a napkin. Back then, I was still with a major corporation, dreaming of becoming the next Wozniak. Six months later, I was out, having underestimated the complexities of equity agreements.</p><p>So, here’s what you need to consider before becoming a tech co-founder:</p><h3>1. The Reality Behind Fancy Titles</h3><p>At an early stage, “CTO” is just a title. You’re the coder, tester, deployer, mentor, and sometimes even the salesperson. If you’re enamored by titles but not the grind, reconsider.</p><p>Picture this: one moment you’re debugging code, the next you’re pitching at a trade show. Can you handle that?</p><h3>2. The Co-Founder Match</h3><p>Your relationship with your co-founder is crucial. Treat it like a serious relationship — look for red flags, give it time, and ensure compatibility. Unlike a spouse, you can’t live with a problematic co-founder.</p><p>No matter how promising the idea, working in a toxic environment is a recipe for disaster.</p><h3>3. Market Segment</h3><p>Understanding your market is key. Ensure that the business idea addresses a real need and that there’s a demand for your solution.</p><p>Don’t just take your co-founder’s word for it. Conduct independent research, validate the problem statement, and seek evidence to support your hypothesis. Tools like surveys, interviews, and market analysis reports can be invaluable here.</p><h3>4. Business Idea and Validation</h3><p>Your co-founder should have done some initial research and market validation. With today’s low-code tools, creating a Proof of Concept (PoC) is relatively easy.</p><p>Look for signs that your co-founder has validated both the problem and the solution. This demonstrates their ability to hustle and shows that they’re not just looking for a cheap developer to test their ideas.</p><h3>Conclusion</h3><p>Are you ready to take the leap and become a tech co-founder? It’s a challenging yet rewarding journey.</p><p>What other factors do you think are crucial in this decision-making process? Share your thoughts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3d13c5694e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taking Cloudflare Worker Analytics Engine for a spin]]></title>
            <link>https://medium.com/@mailtoankitgupta/taking-cloudflare-worker-analytics-engine-for-a-spin-bf193c6a25e4?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf193c6a25e4</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 11:42:57 GMT</pubDate>
            <atom:updated>2023-10-05T11:46:14.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P76UBRqeB-FGD2Fo" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Cloudflare Workers is a serverless platform that allows you to run JavaScript code on Cloudflare’s edge network.</p><p>If you are using Cloudflare workers and are looking to show analytics from your workers in your SaaS application, you can make use of Cloudflare Worker Analytics.</p><h4>Use Case</h4><p>For my app — <a href="https://slashurl.co/">SlashURL</a>, I need to show link analytics. SlashURL is a fast, scalable URL link shortener built using Cloudflare Workers and Workers KV store.</p><p>Some graphs that I need:</p><ol><li>Time series data for clicks</li><li>Top countries</li><li>Top cities</li><li>.. and more</li></ol><h4>Sending Data</h4><p>Steps:</p><ol><li>Create analytics data set binding</li><li>Define metrics &amp; dimensions to send</li><li>Call from within the workers</li></ol><pre>export interface Env {<br>    ...<br>    URL_CLICK_TRACKING: AnalyticsEngineDataset<br>}<br><br>// request.url contains the short original url<br>log(request: Request&lt;unknown, CfProperties&lt;unknown&gt;&gt;): Promise&lt;void&gt; {<br>    const cfProperties = request.cf<br>    if (!cfProperties) {<br>        return Promise.resolve()<br>    }<br><br>    this.env.URL_CLICK_TRACKING.writeDataPoint({<br>        &#39;blobs&#39;: [<br>            request.url,<br>            cfProperties.city as string,<br>            cfProperties.country as string,<br>            cfProperties.continent as string,<br>            cfProperties.region as string,<br>            cfProperties.regionCode as string,<br>            cfProperties.timezone as string<br>        ],<br>        &#39;doubles&#39;: [<br>            cfProperties.metroCode as number,<br>            cfProperties.longitude as number,<br>            cfProperties.latitude as number<br>        ],<br>        &#39;indexes&#39;: [<br>            cfProperties.postalCode as string,<br>        ]<br>    })<br>    return Promise.resolve()<br>}</pre><h4>Querying Data</h4><p>Steps:</p><ol><li>Generate API token to access worker analytics (from Cloudflare console)</li><li>Make a cURL request to the endpoint using the API token like:</li></ol><p>Example SQL Query to get the time series data of clicks:</p><p>The query is trying to count the clicks on a specific URL within 24-hour intervals over the past 30 days, providing a time-series-like result with the number of clicks in each interval (day).</p><p>intDiv is the function to create these 24-hour intervals</p><pre>SELECT intDiv(toUInt32(timestamp), 86400) * 86400 AS t, COUNT() as clicks FROM URL_CLICK_TRACKING WHERE blob1 = &#39;https://slsh.ws/ankit-linkedin&#39; AND timestamp &gt;= NOW() - INTERVAL &#39;30&#39; DAY GROUP BY t ORDER BY t, clicks DESC</pre><pre>curl --location --request POST &#39;https://api.cloudflare.com/client/v4/accounts/7bc1ff972e6f19acd7874cd1f12eff9b/analytics_engine/sql&#39; \<br>--header &#39;Authorization: Bearer &lt;token&gt;&#39; \<br>--header &#39;Content-Type: text/plain&#39; \<br>--data-raw &#39;&lt;query&gt;&#39;</pre><h4>Integrating into Next.js App</h4><p>If you want to feed this data into your Next.js App, you can create a route analytics/[url].tsxusing the page router in Next.js like below:</p><pre>import { ClickStream } from &quot;@/components/analytics/ClickStream&quot;;<br>import Layout from &quot;@/components/layout&quot;;<br>import { getClickStream } from &quot;@/lib/queries&quot;;<br>import {<br>  Alert,<br>  AlertIcon,<br>  Box,<br>  HStack,<br>  Heading,<br>  Stack,<br>} from &quot;@chakra-ui/react&quot;;<br>import { format, fromUnixTime } from &quot;date-fns&quot;;<br>import { GetServerSidePropsContext } from &quot;next&quot;;<br><br>export default function Analytics({ props, analytics }) {<br>  const clickStream = analytics.clickStream;<br>  const noData = clickStream.data.length === 0;<br>  const data = clickStream.data.map((d) =&gt; {<br>    return {<br>      date: format(fromUnixTime(d.t), &quot;dd/M&quot;),<br>      clicks: parseInt(d.clicks),<br>    };<br>  });<br><br>  return (<br>    &lt;Box bg={&quot;white&quot;} py={7} px={7}&gt;<br>      &lt;Stack spacing={2}&gt;<br>        &lt;Heading as=&quot;h1&quot; fontSize=&quot;3xl&quot;&gt;<br>          Analytics<br>        &lt;/Heading&gt;<br>        &lt;HStack mt={5}&gt;<br>          {noData ? (<br>            &lt;Alert status=&quot;info&quot; mt={5}&gt;<br>              &lt;AlertIcon /&gt;<br>              Detailed Analytics for your links will be available soon.<br>            &lt;/Alert&gt;<br>          ) : (<br>            &lt;ClickStream data={data} /&gt;<br>          )}<br>        &lt;/HStack&gt;<br>      &lt;/Stack&gt;<br>    &lt;/Box&gt;<br>  );<br>}<br><br>Analytics.getLayout = function getLayout(page: any) {<br>  return &lt;Layout&gt;{page}&lt;/Layout&gt;;<br>};<br><br>export const getServerSideProps = async (<br>  context: GetServerSidePropsContext<br>) =&gt; {<br>  const { params } = context;<br>  const clickStream = await getClickStream(params.url as string);<br><br>  return {<br>    props: {<br>      analytics: {<br>        clickStream,<br>      },<br>    },<br>  };<br>};</pre><p>To get the data from the Worker Analytics Engine:</p><pre>import axios from &quot;axios&quot;;<br><br>const TIMESERIES_GET_CLICKS = function (url: string) {<br>  return `<br>SELECT<br>  intDiv(toUInt32(timestamp), 86400) * 86400 AS t,<br>  COUNT() as clicks<br>FROM URL_CLICK_TRACKING<br>WHERE<br>  blob1 = &#39;${url}&#39; AND<br>  timestamp &gt;= NOW() - INTERVAL &#39;30&#39; DAY<br>GROUP BY t<br>ORDER BY t, clicks DESC`<br>}<br><br>export async function getClickStream(url: string) {<br>  const API_ENDPOINT = `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/analytics_engine/sql`;<br><br>  const options = {<br>    headers: {<br>      &quot;Authorization&quot;: `Bearer ${process.env.CLOUDFLARE_ANALYTICS_API_TOKEN}`,<br>      &quot;Content-Type&quot;: &quot;text/plain&quot;,<br>    },<br>  };<br><br>  const payload = TIMESERIES_GET_CLICKS(url);<br><br>  let data = null<br>  try {<br>    const response = await axios.post(API_ENDPOINT, payload, options);<br>    data = response.data;<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  }<br><br>  return data<br>}</pre><p>For rendering the charts, we are using the <a href="https://recharts.org/">recharts</a> react library. There are other libraries like <a href="https://react-chartjs-2.js.org/">https://react-chartjs-2.js.org/</a> as well, but I went with this as it supports a lot of charts.</p><p>To create a time series click-stream chart component</p><pre>// Clickstream.tsx<br>import { useEffect, useState } from &quot;react&quot;;<br>import {<br>  CartesianGrid,<br>  Legend,<br>  Line,<br>  LineChart,<br>  Tooltip,<br>  XAxis,<br>  YAxis,<br>} from &quot;recharts&quot;;<br><br>// This is needed as nextjs throws hydration error with recharts rendered on server/client<br>// More: https://github.com/recharts/recharts/issues/2272<br>// So we render it only on client here<br>export const useIsServerSide = () =&gt; {<br>  const [isServerSide, setIsServerSide] = useState(true);<br><br>  useEffect(() =&gt; {<br>    setIsServerSide(false);<br>  }, [setIsServerSide]);<br><br>  return isServerSide;<br>};<br><br>export const ClickStream = (props: Props) =&gt; {<br>  const isServerSide = useIsServerSide();<br>  if (isServerSide) return null;<br><br>  const { data } = props;<br><br>  return (<br>    &lt;LineChart<br>      width={500}<br>      height={300}<br>      data={data}<br>      margin={{<br>        top: 5,<br>        right: 30,<br>        left: 20,<br>        bottom: 5,<br>      }}<br>    &gt;<br>      &lt;CartesianGrid strokeDasharray=&quot;3 3&quot; /&gt;<br>      &lt;XAxis dataKey=&quot;date&quot; /&gt;<br>      &lt;YAxis /&gt;<br>      &lt;Tooltip /&gt;<br>      &lt;Legend /&gt;<br>      &lt;Line type=&quot;monotone&quot; dataKey=&quot;clicks&quot; stroke=&quot;#82ca9d&quot; /&gt;<br>    &lt;/LineChart&gt;<br>  );<br>};</pre><h4>Demo</h4><p>Below is how it looks. Link to the dashboard here: <a href="https://slashurl.co/dashboard">slashurl.co</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npmD01WLnZS3BwnNadkCoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpsYEe15lOawMcAfXkEk_w.png" /><figcaption>Analytics for Clicks</figcaption></figure><h4>References</h4><p><a href="https://developers.cloudflare.com/analytics/analytics-engine/get-started/">https://developers.cloudflare.com/analytics/analytics-engine/get-started/</a></p><p><a href="https://developers.cloudflare.com/analytics/analytics-engine/sql-api/">https://developers.cloudflare.com/analytics/analytics-engine/sql-api/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf193c6a25e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-hosted url shortener using Cloudflare]]></title>
            <link>https://medium.com/@mailtoankitgupta/self-hosted-url-shortener-using-cloudflare-36383ff300c0?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/36383ff300c0</guid>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[link-shortener]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <category><![CDATA[url-shorteners]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 03:34:25 GMT</pubDate>
            <atom:updated>2023-10-07T18:38:25.818Z</atom:updated>
            <content:encoded><![CDATA[<h4>A serverless solution using Cloudflare Workers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UjjL1xxciGSJmeuB" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In this article, we will learn how to build and deploy your own URL shortener on a serverless platform by Cloudflare.</p><p>Cloudflare provides a CDN network, DDoS mitigation, and other cybersecurity products primarily but they have offerings that enable running cloud applications on edge locations (near to the user geographically).</p><h4>Why serverless?</h4><p>While self-hosted is appealing it’s quite messy managing your server and the configurations, especially if you are running your business solo.</p><p>Before we begin, you can check out a demo-hosted version here: <a href="https://slashurl.co/">slashurl.co</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZJZqxIfHa9SRS1CktmIuQ.png" /><figcaption>Dashboard view</figcaption></figure><blockquote>Disclaimer: I am the founder of slashurl and this web version is useful if you would not like to self-deploy</blockquote><p>Let’s begin!</p><h4>Prerequisites</h4><ol><li>Cloudflare Account (with a free tier)</li><li>Dynamo DB (if you would like an incremental ID generator, more on it later)</li><li>Supabase (for storing the web app metadata in Postgresql, free plan)</li><li>Vercel (for deploying the web app, free plan)</li></ol><p><strong>Cloudflare Workers — </strong>Cloudflare Workers is a serverless platform that allows you to run JavaScript code on Cloudflare’s edge network.</p><p><strong>Workers KV — </strong>Workers KV is a key-value store that is built into Cloudflare Workers. It is a great way to store data that you want to access from your Workers.</p><p><strong>AWS DynamoDB — </strong>AWS DynamoDB is a NoSQL database that is built into AWS.</p><p><strong>Supabase — </strong>Supabase is an open-source alternative to Firebase that provides a suite of tools for building scalable web and mobile applications. It provides a set of backend services, including a PostgreSQL database, authentication, and real-time subscriptions, that can be used to build modern applications.</p><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*Cd3tHm8JAwqkk4ojcmnEng.png" /></figure><p>We use Workers KV to store the key-&gt;value and the Workers for the redirection.</p><p>Optionally, we use DynamoDB for incrementally generated unique IDs, and Supabase for storing the click metrics.</p><p>There are a few parts to this tutorial, so breaking it into different sections.</p><h4>Generating unique shortcodes</h4><p>There are multiple approaches to generating the shortcode.</p><p><strong>Approach 1</strong></p><p>Use a uuid generator and truncate to the max length of the URL shortcode you would prefer.</p><p>This approach can lead to duplicates, and so you need to check before inserting the data into the key, value store.</p><p><strong>Approach 2</strong></p><p>Use an incremental counter and convert that into base62 encoded string which is used as a short code.</p><p>This counter should be atomically incremented for it to truly scale. Below is the code to do that with DynamoDB.</p><p>Table — Short_Urls</p><p>Fields: domain and id</p><pre>// file: idgenerator.ts<br>...<br>docClient: DynamoDBDocumentClient;<br><br>async incrementId(domain: string) {<br>    const input = {<br>        TableName: &quot;Short_Urls&quot;,<br>        Key: {<br>            &quot;domain&quot;: domain,<br>        },<br>        UpdateExpression: &quot;SET id = if_not_exists(id, :start) + :incr&quot;,<br>        ExpressionAttributeValues: {<br>            &quot;:start&quot;: 0,<br>            &quot;:incr&quot;: 1,<br>        },<br>        ReturnValues: &quot;UPDATED_NEW&quot;,<br>    }<br>    const command = new UpdateCommand(input);<br><br>    const response = await this.docClient.send(command);<br>    return response;<br>}<br><br>async generateShortUrl(domain?: string) {<br>    if (!domain) {<br>        domain = DEFAULT_DOMAIN;<br>    }<br>    const id = await this.incrementId(domain);<br>    let code = base62Encode(id.Attributes.id);<br>    return `${domain}/${code}`;<br>}</pre><p><strong>Note: </strong>An atomic counter can also be developed using Cloudflare Durable Objects as well. Here is a <a href="https://developers.cloudflare.com/durable-objects/examples/build-a-counter/">link</a> to the documentation.</p><h4>REST APIs</h4><p>There are a few approaches here to publish the API to generate the short urls:</p><p><strong>Approach 1</strong></p><p>Create the function to generate the short link inside Cloudflare Workers itself. This can work if you plan to generate links via API only.</p><p><strong>Approach 2</strong></p><p>Use Next.js-based APIs to serve the traffic to perform CRUD operations on the URLs — create, edit, delete</p><p>And publish the key, value to Worker KV for faster retrieval.</p><p>Approach 2, is useful if you plan to host your own web app and want to manage your links from it.</p><p><strong>Generate short URL — API</strong></p><p>Payload Schema for POST /urls/create</p><pre>export interface UrlItemReq {<br>  id?: number;<br>  userId: string;<br>  longUrl: string;<br>  domain?: string;<br>  slug?: string;<br>};<br><br>export interface UrlItemRes {<br>    shortUrl: string;<br>    longUrl: string;<br>};</pre><p>slug is an optional param that can be used to save custom back half for short links instead of the base62 encoded strings</p><p>domain is an optional param to generate the shortcode for a particular custom domain</p><p>If you plan to store your data in Supabase, below is the schema for urlstable</p><pre>create table<br>  public.urls (<br>    id bigint generated by default as identity,<br>    created_at timestamp with time zone null default now(),<br>    short_url text not null,<br>    long_url text not null,<br>    expiry timestamp with time zone null,<br>    clicks bigint null default &#39;0&#39;::bigint,<br>    user_id uuid null,<br>    constraint short_urls_pkey primary key (id),<br>    constraint short_urls_short_url_key unique (short_url),<br>    constraint urls_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade<br>  ) tablespace pg_default;</pre><p>On to the code for the API handler —</p><pre>// file: create.ts<br>...<br>async createItem(supabase: SupabaseClient, itemData: UrlItemReq): Promise&lt;UrlItemRes&gt; {<br>    const { userId, domain = DEFAULT_DOMAIN, longUrl, slug } = itemData;<br>    let shortUrl: string;<br>    if (slug) {<br>        shortUrl = domain + &quot;/&quot; + slug;<br>    } else {<br>        shortUrl = await this.idGenerator.generateShortUrl(domain);<br>    }<br><br>    const shortUrlWithHttps = &quot;https://&quot; + shortUrl;<br>    // optional if we need the backend to manage the links<br>    const { data, error } = await supabase<br>            .from(&#39;urls&#39;)<br>            .create([<br>                { userId, shortUrl: shortUrlWithHttps, longUrl }<br>            ])<br>            .select();<br>    <br>    // this updates the cloudflare kv with the short-&gt;long url mapping<br>    await this.kvStore.put(shortUrl, longUrl);<br>    return data;<br>}<br><br>export default async (req, res) =&gt; {<br>    const supabaseClient = createPagesServerClient({ req, res })<br>    const { data: { user } } = await supabaseClient.auth.getUser();<br><br>    try {<br>        const item = await createItem(supabaseClient, {<br>            userId: user ? user.id : null,<br>            id: req.body.id,<br>            longUrl: req.body.longUrl,<br>            slug: req.body.slug,<br>        });<br>        res.status(200).json(item[&quot;short_url&quot;]);<br>    } catch (error) {<br>        res.status(400).json({ error: error.message });<br>    }<br>}</pre><p><strong>Note</strong>: I have skipped validation for the payload for simplicity.</p><h4>Redirection Workers</h4><p>Add the below code for the redirection workers</p><pre>// file: index.ts<br>...<br>urlKv: KVNamespace; <br>getShortCode(request: Request): string {<br>    // trim prefix https from url<br>    return request.url.replace(/^https?:\/\//, &quot;&quot;);<br>}<br><br>async function handler(request: any, env: Env, ctx: ExecutionContext) {<br> try {<br>    const shortCode = this.getShortCode(request);<br>    const trackUrl = (await this.urlKv.get(shortCode)) as string;<br>    if (!trackUrl) {<br>        return new Response(&quot;Short URL not found&quot;, { status: 404 });<br>    }<br>    return Response.redirect(trackUrl);<br> } catch (error) {<br>    return new Response(&quot;Internal Server Error&quot;, { status: 503 });<br> }<br>}<br><br>// Process the short urls<br>router.get(&quot;/:code&quot;, handler)</pre><p>The mapping in Cloudflare is stored including the domain, to handle custom domains, hence we use the request.url to get the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgK04xnmwP7M7nY73gGloQ.png" /></figure><p>This retrieves the long URL from the kv and redirects the user to it using 302 redirects.</p><h4>Updating click metrics</h4><p>We have a few choices here as well.</p><p><strong>Approach 1</strong></p><p>Update the click counters in the kv metadata directly. Here is more <a href="https://developers.cloudflare.com/workers/runtime-apis/kv/#metadata">documentation</a> on it.</p><p><strong>Approach 2</strong></p><p>If however, you are going to use it like a LMS, then saving the click counters alongside the link data in the database will make the view in the frontend a breeze.</p><p>To do this, you need to update the redirection worker handler with:</p><pre>async incrementClicks(shortUrl: string, clicks: number): Promise&lt;void&gt; {<br>    const { data, error } = await this.supabase<br>        .rpc(&#39;increment_clicks&#39;, { url: shortUrl, counter: clicks });<br><br>    if (error) {<br>        console.error(&quot;error updating tracking: &quot;, JSON.stringify(error));<br>    }<br>}<br><br>async function shortUrlHandler(request: any, env: Env, ctx: ExecutionContext) {<br> try {<br>    ...<br>    // this doesn&#39;t block the click increment while performing redirection<br>    this.ctx.waitUntil(incrementClicks(request.url, 1))<br>    return Response.redirect(trackUrl);<br> }<br> ..<br>}</pre><p>Also, we need a RPC increment_clicks in Supabase:</p><pre>create function increment_clicks (counter int, url text) <br>returns void<br>security definer<br>as $$<br>  update urls <br>  set clicks = clicks + counter<br>  where short_url = url<br>$$ <br>language sql volatile;</pre><p>We do this instead of directly updating the click metrics since the anonymous access will fail the authorization to update the URL counter in the table. So we implement this via a stored procedure in PostgreSQL.</p><p>And voila! You have created a fully functional URL shortener hosted on the serverless platform Cloudflare.</p><p>Note: If you wish to extend this with custom domains, you can do this using <a href="https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/">Cloudflare for SaaS</a></p><p>Building the frontend that connects with the PostgreSQL backend in Supabase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZJZqxIfHa9SRS1CktmIuQ.png" /><figcaption>Dashboard built using Next.js/Chakra UI</figcaption></figure><p>This is outside the scope of this tutorial but if you are interested in the full code for it you can contact me at <a href="/service/mailto:slashurlco@gmail.com">slashurlco@gmail.com</a> and I will help to deploy this at the <a href="https://www.buymeacoffee.com/slashurl">cost of a Coffee</a> :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36383ff300c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang gRPC API Benchmarking: How to Measure and Improve Performance]]></title>
            <link>https://medium.com/@mailtoankitgupta/golang-grpc-api-benchmarking-how-to-measure-and-improve-performance-9dab4b8a933?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dab4b8a933</guid>
            <category><![CDATA[pprof]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 03:38:04 GMT</pubDate>
            <atom:updated>2023-06-11T09:20:32.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kP8GgKqcmgNWfP97" /><figcaption>Photo by <a href="https://unsplash.com/@marcsm?utm_source=medium&amp;utm_medium=referral">Marc Sendra Martorell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>gRPC APIs (Application Programming Interfaces) are a type of remote procedure call (RPC) framework that enables the communication between different services in a distributed system. It uses the Protocol Buffers (protobufs) language for defining both the service interface and the structure of the payload messages.</p><h3>Problem</h3><p>The gRPC API had a new layer of authorization, hence it had to be benchmarked for varying <em>sizes</em> of resources served via the <em>GetAll</em> endpoint.</p><h4>How to benchmark?</h4><p>Writing a benchmark test in Go is simple enough. Go provides a built-in package called “testing” that includes a sub-package called “benchmark” that makes it easy to write benchmark tests.</p><pre>...<br>func BenchmarkGetAll(b *testing.B) {<br> // do any test setup if required<br> // in this case we get the ctx, conn and client for the grpc method to call<br> ctx, conn, client := setUp(b)<br> defer conn.Close()<br><br> inputSizes := []int{10, 100, 1000}<br> for _, size := range inputSizes {<br>  b.Run(fmt.Sprintf(&quot;size_%d&quot;, size), func(b *testing.B) {<br>   b.ResetTimer()<br>   for i := 0; i &lt; b.N; i++ {<br>    callGetAll(b, ctx, client)<br>   }<br>  })<br> }<br>}</pre><pre>go test -run=&#39;^$&#39; -bench=BenchmarkGetAll -benchtime=10x -count=6 -timeout 60m &gt; debug.profile</pre><p>Using benchstat to compare the old and new performance</p><pre>$ benchstat profile.old profile.new<br>goos: linux<br>goarch: amd64<br>cpu: Intel(R) Xeon(R) CPU E5-2640 v3 @ 2.60GHz<br><br>               │   profile.old     │                 profile.new                  │<br>                     │    sec/op     │     sec/op      vs old                   │<br>GetAll/size_10-32     180.51m ± 13%    1819.20m ± 10%   +908.74% (p=0.002 n=6)<br>GetAll/size_100-32    160.51m ± 21%    1608.78m ±  5%   +902.07% (p=0.002 n=6)<br>GetAll/size_1000-32   210.73m ± 49%    2098.44m ±  8%   +896.68% (p=0.002 n=6)<br>geomean               174.57m ± 13%  </pre><p>The benchmarks revealed that the performance dropped by 10x on average.</p><h4>Measuring code performance using pprof</h4><blockquote>pprof is a tool for visualization and analysis of profiling data.</blockquote><p>To analyze where the code is spending time and how we can improve, one can install <a href="https://github.com/google/pprof">pprof</a> using go install github.com/google/pprof@latest</p><p>To generate pprof profile for our gRPC API, follow the below steps:</p><ol><li>Add the below import to the file where you have started the grpc server</li></ol><p>import _ “net/http/pprof”</p><p>2. Start the debug server alongside the main API .Serve()</p><pre> ...<br> g.Go(func() error {<br>  return http.ListenAndServe(&quot;:10001&quot;, nil)<br> })</pre><p>3. You can generate the profile using curl (or any other tool)</p><p>curl -o debug.profile &lt;ip&gt;:10001/debug/pprof/profile?seconds=5</p><p>The above command captures the profile for 5s and dumps the profile in debug.profile file</p><h4>Identifying areas of improvement</h4><p>Useful commands to analyze pprof</p><pre>$ pprof debug.profile <br>&gt; list myMethodName # shows the line by line analyses<br><br>$ pprof -web debug.profile # opens the web visualization tool<br>$ pprof -top debug.profile # shows the top functions based on the cumulative time</pre><p>Few general guidelines to fix issues:</p><ol><li>Preallocation — If copy operations are taking time, check if you can pre-allocate the slices, and maps preventing dynamic re-allocation using make</li><li>Goroutines — If there are external operations (calls to db, any other API) that take time, see if those can be parallelized using Goroutines.</li><li>Caching — while it seems quite obvious, sometimes there can be frequent operations involving the same inputs that can be optimized via a local or even an API request level cache [1]</li></ol><h4>Re-running the pprof, and benchmarks</h4><p>You can re-run the pprof, obtain the profile again, and analyze it. Re-run your benchmarks to see if the performance is satisfactory.</p><p>After fixing a few of the issues, the performance returned to around 2-3x the original time which was an improvement.</p><pre>$ benchstat profile.old profile.new<br>goos: linux<br>goarch: amd64<br>cpu: Intel(R) Xeon(R) CPU E5-2640 v3 @ 2.60GHz<br>                     │ profile.old  │  profile.new    │<br>                                    │    sec/op    │    sec/op     vs base                │<br>GetAll/size_10-32     130.3m ±  7%   309.4m ± 44%  +137.44% (p=0.002 n=6)<br>GetAll/size_100-32    148.4m ± 11%   453.1m ±  7%  +205.25% (p=0.002 n=6)<br>GetAll/size_1000-32   247.1m ± 10%   965.8m ± 54%  +556.61% (p=0.002 n=6)<br>geomean               141.7m         513.5m        +262.39%</pre><p>We can further iterate and stop when things look satisfactory.</p><p>Fin.</p><p>[1] API request level caching can be used if we don’t want to maintain a cache that can get stale, instead simply serve repeated data queries for this particular request via it.</p><p>If you liked this, connect with me on <a href="https://www.linkedin.com/in/ankitgupta90/">LinkedIn</a> or <a href="https://twitter.com/_AnkitGupta">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dab4b8a933" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redirecting k8s container logs to systemd-journal]]></title>
            <link>https://medium.com/@mailtoankitgupta/redirecting-containerd-logs-to-systemd-journal-6f8bf3fa5f0c?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f8bf3fa5f0c</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[systemd]]></category>
            <category><![CDATA[containerd]]></category>
            <category><![CDATA[fluentbit]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 03:24:53 GMT</pubDate>
            <atom:updated>2023-06-11T09:21:29.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ub9W83q0OVjDlOoH" /><figcaption>Photo by <a href="https://unsplash.com/@ventiviews?utm_source=medium&amp;utm_medium=referral">Venti Views</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With <a href="https://kubernetes.io/blog/2020/12/02/dockershim-faq/">Kubernetes ending support for dockershim</a>, I recently required to move from Docker to Containerd as the runtime for the containers in the pods.</p><p>Docker already comes with a logging driver — meaning you can move your logs to systemd-journal, cloud watch, etc by just configuring the options for these.</p><p>With Containerd and similar runtimes (like <a href="https://cri-o.io/">cri-o</a>), the responsibility to collect and redirect logs to your choice of log aggregation tool is left to the user.</p><p>Thankfully with frameworks like fluentbit one can restore a lot of the functionality that Docker logging driver provided.</p><p>In this post I am going to talk about how to redirect your logs to systemd-journal via a custom Go plugin in Fluent Bit on your Kubernetes Cluster.</p><p><a href="https://fluentbit.io/">Fluent Bit</a> provides a way to aggregate logs from source(s) to destination(s). The pluggable framework makes it easy to collect, parse, filter and then stream them to your choice of log aggregator — Elastic Search, Grafana Loki, Prometheus etc.</p><p>Fluent Bit unlike its predecessor <a href="https://www.fluentd.org/">fluentd</a> is quite light weight (<a href="https://docs.fluentbit.io/manual/about/fluentd-and-fluent-bit">650 Kb vs 40 Mb in runtime memory</a>) and offers more configurable options to plug source/destinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLbn7pS4O5hA_Wu6jkACCA.png" /><figcaption>src: fluentbit.io</figcaption></figure><p><strong>Why custom plugin?</strong> Because fluent bit doesn’t provide a plugin for <em>systemd-journal</em> as the sink for logs. This is not a popular choice for log aggregation but one that was being used at my place of work.</p><p>Let’s get started.</p><h3>Creating the go module</h3><ol><li>Create a dir systemd-journaland do a go mod init</li><li>Install the go mods coreos/go-systemd, fluent-bit-go</li><li>Create a new file out_systemd_journal.gothis will contain the main plugin code</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7b87b54dc7752e7a41d5a4a07deee5/href">https://medium.com/media/df7b87b54dc7752e7a41d5a4a07deee5/href</a></iframe><h3>Building the Fluent Bit Image</h3><p>1. Creating a Makefile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37c969be8d6e6edc340a1dc83c88d50/href">https://medium.com/media/c37c969be8d6e6edc340a1dc83c88d50/href</a></iframe><p>2. Create a Dockerfile to build an image of fluentbit containing this plugin .so loaded</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19cad94febc316fb311e08f317386114/href">https://medium.com/media/19cad94febc316fb311e08f317386114/href</a></iframe><p><strong>Note</strong>: You could also build the plugin within the Dockerfile itself</p><p>3. Run make build_image target</p><p>Once the image is built one can use this image in the output plugin DaemonSet for elasticsearch, loki etc</p><h3>Configuring the fluent-bit.conf</h3><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: fluent-bit-config<br>  namespace: kube-system<br>  labels:<br>    app: fluent-bit<br>data:<br>  # Configuration files: server, input, filters and output<br>  # ======================================================<br>  fluent-bit.conf: |<br>    [SERVICE]<br>        Flush         1<br>        Log_Level     info<br>        Daemon        off<br>        Parsers_File  parsers.conf<br>        HTTP_Server   On<br>        HTTP_Listen   0.0.0.0<br>        HTTP_Port     2020</pre><pre><a href="http://twitter.com/INCLUDE">@INCLUDE</a> input-kubernetes.conf<br><a href="http://twitter.com/INCLUDE">@INCLUDE</a> filter-kubernetes.conf<br><a href="http://twitter.com/INCLUDE">@INCLUDE</a> filter-nest.conf<br><a href="http://twitter.com/INCLUDE">@INCLUDE</a> output-systemd-journal.conf</pre><pre>input-kubernetes.conf: |<br>    [INPUT]<br>        Name              tail<br>        Tag               kube.*<br>        Path              /var/log/containers/*.log<br>        Exclude_Path      /var/log/containers/fluent*.log<br>        Parser            cri<br>        DB                /var/log/flb_kube.db<br>        Mem_Buf_Limit     5MB<br>        Skip_Long_Lines   On<br>        Refresh_Interval  10</pre><pre>filter-kubernetes.conf: |<br>    [FILTER]<br>        Name                kubernetes<br>        Match               kube.*<br>        Kube_URL            <a href="https://kubernetes.default/">https://kubernetes.default</a><br>        Kube_CA_File        /var/run/secrets/kubernetes.io/serviceaccount/ca.crt<br>        Kube_Token_File     /var/run/secrets/kubernetes.io/serviceaccount/token<br>        Kube_Tag_Prefix     kube.var.log.containers.<br>        Merge_Log           On<br>        Merge_Log_Key       log_processed<br>        K8S-Logging.Parser  On<br>        K8S-Logging.Exclude Off<br>        tls.verify          Off</pre><pre>filter-nest.conf: |<br>    [FILTER]<br>        Name                nest<br>        Match               kube.*<br>        Operation           lift<br>        Nested_Under        kubernetes</pre><pre>output-systemd-journal.conf: |<br>    [OUTPUT]<br>        Name                systemd_journal<br>        Match               kube.*</pre><pre>parsers.conf: |<br>    [PARSER]<br>        # <a href="http://rubular.com/r/tjUt3Awgg4">http://rubular.com/r/tjUt3Awgg4</a><br>        Name cri<br>        Format regex<br>        Regex ^(?&lt;time&gt;[^ ]+) (?&lt;stream&gt;stdout|stderr) (?&lt;logtag&gt;[^ ]*) (?&lt;message&gt;.*)$<br>        Time_Key    time<br>        Time_Format %Y-%m-%dT%H:%M:%S.%L%z</pre><p><strong>Note 1</strong>: This assumes you are running Fluent Bit within the K8s stack and using config maps for the fluent-bit.conf</p><p><strong>Note 2</strong>: We perform some parsing &amp; un-nesting to extract the kubernetes fields in the logs before forwarding to systemd-journal</p><p>Fin.</p><h3>References</h3><p><a href="https://docs.fluentbit.io/manual/development/golang-output-plugins">Golang Output Plugins</a></p><p>If you liked this, connect with me on <a href="https://www.linkedin.com/in/ankitgupta90/">LinkedIn</a> or <a href="https://twitter.com/_AnkitGupta">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f8bf3fa5f0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase functions with Babel & Typescript]]></title>
            <link>https://medium.com/@mailtoankitgupta/firebase-functions-with-babel-typescript-fdf04306aec7?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdf04306aec7</guid>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 02:28:03 GMT</pubDate>
            <atom:updated>2023-06-11T09:22:18.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tObA3rAuri8CPAAK" /><figcaption>Photo by <a href="https://unsplash.com/@juanjodev02?utm_source=medium&amp;utm_medium=referral">Juanjo Jaramillo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Firebase provides the init template to setup the functions directory with Typescript or Javascript. But if you would like to use babel features in the functions you need to setup the code differently.</p><p>Let’s get started!</p><p>You need to create a firebaseFunctions dir within your main package</p><pre>|-- ...<br>|-- firebaseFunctions<br>   |-- index.ts<br>   |-- utilities<br>   |-- .env<br>   |-- package.json<br>   |-- package-lock.json</pre><pre>|-- firebase.json<br>|-- package.json<br>|-- package-lock.json</pre><p><strong>Note 1</strong>: firebase.json contains the service credentials and also an entry to the functions where we can point to the final functions dir to upload to Firebase</p><pre>...<br>&quot;functions&quot;: {</pre><pre>   &quot;source&quot;: &quot;functions&quot;,</pre><pre>   &quot;runtime&quot;: &quot;nodejs16&quot;</pre><pre>}</pre><p>In your root package.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a3173e74d32fb5dcce3103002db9db6/href">https://medium.com/media/2a3173e74d32fb5dcce3103002db9db6/href</a></iframe><p><strong>Note 1:</strong> The package:functions script transpiles the code in the firebaseFunctions dir to functions dir</p><p><strong>Note 2:</strong> The postpackage:functions script runs the npm install since firebase deploy requires that. The node_modules folder is ignored during upload to Firebase</p><p>In your firebaseFunctions package.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d5b8fa322e399420905dcc146f86de7/href">https://medium.com/media/2d5b8fa322e399420905dcc146f86de7/href</a></iframe><p>Finally for compiling TS code in firebaseFunctions you need to configure babel.config.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec793f1c20ea08d8e2c9670163354c1/href">https://medium.com/media/5ec793f1c20ea08d8e2c9670163354c1/href</a></iframe><p><strong>Note 1:</strong> You need to install the associated babel packages in the root package.json</p><h3>References</h3><p><a href="https://github.com/jthegedus/firebase-functions-babel-example">https://github.com/jthegedus/firebase-functions-babel-example</a></p><p>If you liked this, connect with me on <a href="https://www.linkedin.com/in/ankitgupta90/">LinkedIn</a> or <a href="https://twitter.com/_AnkitGupta">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdf04306aec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I found a hack-y way to onboard new joiners]]></title>
            <link>https://medium.com/gramoday/i-found-a-hack-y-way-to-onboard-new-joiners-dd2ec8c201f7?source=rss-46f568b9f95c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd2ec8c201f7</guid>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[onboarding]]></category>
            <category><![CDATA[confluence]]></category>
            <dc:creator><![CDATA[Ankit Gupta]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 03:04:44 GMT</pubDate>
            <atom:updated>2023-06-11T09:22:34.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9FtXocapAOeWAzOU" /><figcaption>Photo by <a href="https://unsplash.com/@schmaendels?utm_source=medium&amp;utm_medium=referral">Andreas Klassen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have onboarded new joinees — employees &amp; interns in your company, you would have realised how repetitive the process is.</p><p>If you lead the person through a structured way to ramp up it can make the experience of the new person quite pleasant and less overwhelming at the same time. We need to ensure that topics are introduced at a time when the employee can understand and absorb it better.</p><p>This needs to be coupled with assigning tasks and making sure they are completed. Once those are done, requisite advanced training on that particular topic can be provided.</p><p>One other problem is — as a mentor you also want to track their progress so as to know where they are.</p><p>Let’s see how to do this, very easily with few tools (that you already maybe using)!</p><p>Documentation is at the heart of making any onboarding path smooth. We use Confluence by Atlassian to document our flows, how-tos, etc.</p><p>For task management we use JIRA (again by Atlassian).</p><h3>Step 1.</h3><p>Document each and everything that you find yourself explaining over and over. Confluence or any other tool like Notion would work equally well here.</p><h3>Step 2.</h3><p>Create a JIRA task (or any other task management tool) with sub-tasks which are either of the 2 types:</p><ol><li>Reading material</li><li>Action / Try out / Task item</li></ol><p>Assign rough estimates on each sub-task — indicating the time it would typically take to complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsKJPvDmwacQMs-2tdIQKw.png" /><figcaption>Onboarding Task</figcaption></figure><p>As the tasks complete one can monitor their progress right from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD4qq6-0eXMhD6DbINDR6Q.png" /><figcaption>Sub-tasks with Action Items</figcaption></figure><p>You can mark tasks Optional to indicate they can be skipped.</p><p>Fin.</p><p>If you liked this, connect with me on <a href="https://www.linkedin.com/in/ankitgupta90/">LinkedIn</a> or <a href="https://twitter.com/_AnkitGupta">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2ec8c201f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gramoday/i-found-a-hack-y-way-to-onboard-new-joiners-dd2ec8c201f7">I found a hack-y way to onboard new joiners</a> was originally published in <a href="https://medium.com/gramoday">Gramoday</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>