<?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 Erik Davtyan on Medium]]></title>
        <description><![CDATA[Stories by Erik Davtyan on Medium]]></description>
        <link>https://medium.com/@erdavtyan?source=rss-39b28d4369b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k2V0XnonOQXVv0NNP8GXbA.jpeg</url>
            <title>Stories by Erik Davtyan on Medium</title>
            <link>https://medium.com/@erdavtyan?source=rss-39b28d4369b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:19:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erdavtyan/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[You Have Always Been Ready]]></title>
            <link>https://medium.com/@erdavtyan/you-have-always-been-ready-2f05d1eebd61?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f05d1eebd61</guid>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 06:53:35 GMT</pubDate>
            <atom:updated>2026-04-27T06:53:35.131Z</atom:updated>
            <content:encoded><![CDATA[<h4>Critique of the prerequisite mindset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ybhewTImjpcCaXSrk_ltQ.png" /></figure><p>Have you thought about starting a YouTube channel? Or reading a hard book? Of course you have. And often, before starting, you decide you first need to get ready.</p><p>I wanted to read Wittgenstein’s Tractatus Logico-Philosophicus. To do this <em>effectively</em>, I decided to understand more of the context that produced the work. To that end, I catalogued every philosophy book I needed to read before it; the overly extensive list included philosophers like Plato, Aristotle, Descartes, Hume, Kant and Russell. I downloaded all the relevant books, and started reading them. My hope was that I would be able to read Wittgenstein by the end of the year, having all the necessary context. But my plan was doomed from the start. I wanted to read Wittgenstein, and my perfectionist mindset created an illusion that I need <strong>strong fundamentals</strong> to understand it better. Strong fundamentals might have helped, but treating them as mandatory was a losing strategy. I never actually got to read all these prerequisite books — because that was not the thing I actually wanted.</p><p>The same thing happened when I wanted to try YouTube. I bought a tripod, a microphone, took a YouTube video course, and started blogging to get better at writing — everything except actually doing YouTube.</p><p>In programming, there is a concept called lazy evaluation. Imagine there is a complicated calculation in your code, which is only needed in some of the future cases. Instead of naïvely evaluating it immediately — called <em>eager</em> evaluation — you can express the calculation but not actually compute it on the spot. Later, when / if the result of that computation is ever needed, the computation will be executed. This way, the expensive computation will only happen on demand.</p><p>A real life example of lazy evaluation is washing vegetables. When you first buy vegetables, you don’t wash all of them. You keep them in the fridge, and only wash the ones that you need when making a salad. The point is not to avoid washing vegetables, but to wash them when washing is necessary.</p><p>Lazy learning is an adaptation of this approach to learning. Instead of building bottom-up, you start with the thing you actually want to do, and learn only the prerequisites that become necessary along the way. This approach has a multitude of advantages. First and foremost — you actually get to do what you want to do. Instead of reading Plato and Aristotle, you read Wittgenstein. Instead of learning how to edit the perfect video — you post something on YouTube and see if you like the process.</p><p>There is another reason to start now: what you want to do is useful information. Acting on it allows you to build on top of it tomorrow. A lot of people don’t even know what they want. Desire gives direction, and over-preparation can waste the motivation window. So use your temporary superpower of possessing this precious information.</p><p>Secondly, this approach helps you iterate more. Instead of wasting time on prerequisites, you get immediate feedback on the thing you actually want. You quickly find out whether you like YouTube or not, find your bottlenecks, and make your next video better. In the book “Atomic Habits” by James Clear, he tells about the quality vs quantity experiment conducted by Jerry Uelsmann, a professor at the University of Florida. In his class “Beginning Photography”, he divided the students into two groups. The first group was graded based on the amount of work they produced (100 photos gets you an A), while the second group needed to submit only one photo, and would be graded on the quality of the image. Unsurprisingly, all the best photos were produced by the quantity group — they got their reps in.</p><p>This is easier said than done. Looking at an empty video editor makes you want to find a tutorial, because watching one is easier than figuring things out. But you probably already lazy learn in many other aspects of your life. People lazy learn their hobbies. Typically, when someone wants to learn to play the guitar, they start from a song they like. And this transforms their goal from “learning how to play the guitar” to “learning how to play my favorite song”, which is technically harder (remember, you don’t possess guitar skills), but far more motivating, and closer to the thing you actually want.</p><p>Another aspect of life where people have to lazy learn is at their jobs. As a software engineer, I face new problems constantly, and have to learn and adapt to solve them. At my job — for which I get paid — this is a must, and I do it all the time. At my previous job I was designated the sole platform engineer, and had to lazy learn all DevOps skills from scratch. Similarly, I recently took on a data engineering role. I have no data engineering experience, but I also have no doubts that I am going to figure it out. You could argue this is because I already possess the fundamentals from my previous experience and degree in computer science. However, I still find it hard to do this in my own projects. I am drawn to tutorials, and want to understand the whole system before I actually make the app.</p><p>There are cases where you need the prerequisite to be able to move forward. You might argue I imply you don’t need any prerequisites to practice medicine, which is false. Lazy learning works best when the cost of mistakes is low and feedback is fast. In those cases it’s better to err on the side of having too few prerequisites. Try to do the thing you actually want, discover the absolutely necessary prerequisites, and only tackle those. The alternative approach isn’t to prepare and start when you are ready, it’s to drain your motivation before you ever get to what you want.</p><p>Start the blog, post your first video, read the hard book. You have always been ready. Do the thing you want to do, instead of the thing surrounding and obstructing the thing you want to do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f05d1eebd61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Won’t Replace Me, Right?]]></title>
            <link>https://medium.com/@erdavtyan/ai-wont-replace-me-right-f158833b0429?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f158833b0429</guid>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 19:40:14 GMT</pubDate>
            <atom:updated>2026-03-31T19:40:14.528Z</atom:updated>
            <content:encoded><![CDATA[<p>AI has continued to grow rapidly, both in competency and in use. Opus 4.6 and GPT 5.4 are both amazing and ushered in the era where I can give a complex task to a model and have it implement the feature end to end. However, programmers have not been replaced on a large scale. This has led some to speculate that with these new tools knowledge work will simply expand — like it did historically with higher level programming languages, and there will be an even larger need for programmers than before. Even if my productivity goes up 100x (which it has not), the argument is that there is “more than 100x software to create”. But the sheer multiplier is not the problem. There is a case to be made that the demand for programmers will go down, even if there is significantly more knowledge work to be done. The danger is moving the bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z69ajqPir9aSxpxw" /><figcaption>Photo by <a href="https://unsplash.com/@zulfugarkarimov?utm_source=medium&amp;utm_medium=referral">Zulfugar Karimov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the past, companies needed to keep many engineers, because the business bottleneck was the software creation. Sales and product decision cycles were much shorter than development times, so companies thought carefully about what to build, relied on simple MVP-s for sales pitches, and decreased the number of features that developers needed to build. However, now that building a product has become cheaper, the bottleneck might be shifting. While AI tools can be used to speed up product and sales cycles as well, it is harder to make the argument that they will see the same high multipliers as dev work. These cycles have a human element — sales calls, compliance meetings, law, etc. — which don’t fall under the umbrella of trivially AI-optimizable activities. So the bottleneck can shift to sales and product cycles, which means devs with AI tooling can implement software quicker than sales / product people can decide what is worth building.</p><p>Assuming dev cycles speed up enough to be faster than sales / product cycles, this shift will definitely put pressure on the demand for programmers. Particularly, there are fields where there is little to no human verification loops in products. These fields include simple CRUD apps, mobile apps, and generally software that can be both built, tested, and verified by an AI. There, product building cycles aren’t tightly bound, and can easily become much faster than the sales / product cycles described above. In these fields, expect programmers to be laid off.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f158833b0429" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should I buy Bitcoin now or wait for a better price?]]></title>
            <link>https://medium.com/@erdavtyan/should-i-buy-bitcoin-now-or-wait-for-a-better-price-31cac07d61f8?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/31cac07d61f8</guid>
            <category><![CDATA[cryptocurrency-investment]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 17:51:47 GMT</pubDate>
            <atom:updated>2025-09-01T17:51:47.375Z</atom:updated>
            <content:encoded><![CDATA[<p>This question has been plaguing my mind since BTC crossed $100k in late 2024. By delaying the decision to buy, it seemed like I was both losing out on its meteoric rise, and avoiding the inevitable collapse. Fast forward to today, when the price is at 108k, 13% lower than the All-Time High of 124k, the question remains standing: Should I buy BTC now, or wait for a further drop in price?</p><p>To start with, I want to clarify that while Bitcoin is a risky asset, I am bullish on it long-term. I can see it’s the hardest and most antifragile kind of money — better than gold in every criteria that matters. It is more easily divisible, much easier to transport (in fact, to transport BTC to another country, all you have to do is… nothing. It is inherently cross-border), easier to keep safe, has more controlled inflation and is less centralized. It’s the dream of libertarian thinkers like Rothbard and Hayek, who in 20th century predicted that we will soon have currency that states don’t control directly. As per their prediction, the market shows that it does like such kind of money — and thus we see the rise of Bitcoin.</p><p>Even though I know I want to have Bitcoin, I don’t know when I should buy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9bL_CGUWDwYHjbuw.jpeg" /></figure><p>Ideally, I want to avoid being this guy from both ends. I want to always buy low. The strategy I came up with is to simply not buy Bitcoin if it’s within 20% of All-Time High. This way I’d let it rise, and then buy at a discount when it falls. Sounds like a good idea, let’s try it out!</p><h3>Experiment</h3><p>So I decided to do a little bit of time traveling. I downloaded BTC daily prices from 2020–2025, and ran a few trading experiments on it. I used <a href="https://www.anthropic.com/claude-code">Claude Code</a> to write a few Python scripts each representing a strategy. Feel free to fork my <a href="https://github.com/erodactyl/backtesting-btc-trading-strategies">code</a> and do some experiments of your own, I’d love to see the results.</p><p>For each strategy the agent gets $1 per day. It can see the historical price of Bitcoin, and come up with any strategy to trade it each day. Here are the 3 strategies I tested out:</p><ol><li>First is the naive Dollar Cost Averaging strategy. Each day, the agent purchases $1 worth of Bitcoin.</li><li>The second agent tracks the moving average price of Bitcoin, and only buys when today’s price is lower than the moving average. It accumulates the money on the days when it’s higher, to buy at a lower price later.</li><li>Last, but not least, is the “clever” strategy I outlined above. That one accumulates money like the second one, and only buys when the current price of BTC is 20% lower than the All Time High.</li></ol><p>There is a lot to improve in my experiment, of course. The most glaring omission is the ability to sell — none of the strategies I tested had the option to sell BTC. But even with this simple setup, there is a lot to notice and learn from.</p><h3>Findings</h3><p>As every investment guru and Bitcoin YouTuber would have predicted, Dollar Cost Averaging won. At the end of the 5 year period, the <strong>DCA agent</strong> had 0.05557 BTC, the <strong>moving average agent</strong> had 0.05463 BTC, and the <strong>ATH dip agent </strong>only had 0.04853 BTC (and some cash on hand that it had accumulated). DCA agent has outperformed the other strategies for this time period. But why is that? How come when we buy lower we don’t get a higher return?</p><p>Let’s look at a simple example. Assume we are the ATH dip agent, and the price of BTC is currently $60k, which is the ATH at the moment. So, we don’t buy, we accumulate. The price rises to $70k, we still don’t buy. The price blows past $80k, $90k, $100k, setting new ATH records, and we still don’t buy. Then, the price drops to $80k. Nice! It’s more than 20% lower than it’s ATH of 100k, so it’s time to buy “cheap” BTC.</p><p>Did you see what happened there? We missed out on buying at $60k-$80k, and instead jumped at the opportunity to buy at $80k. DCA would not have missed this opportunity.</p><p>Unsurprisingly, the absolute best strategy for this trading period is actually <strong>NOT </strong>DCA. It’s a lump-sum buy. The agent that sold its house and car and put everything in BTC on day 1 wins the most amount of money. But this only works because the market was bullish, and could have easily backfired in a bearish or sideways market. Moreover, in real life we often get our money periodically, not all at once — in the form of salaries, so it’s much easier to think about DCA strategies. As with many other backtesting strategies on crypto and stock market investments — the simplest approach wins in a bull market.</p><p>The ATH dip and moving average agents can perform exceptionally well in a more volatile market. But in a bull market, when prices rise, DCA-ing is the safest, and often the most rewarding strategy. In such a market trying to time your buys can and will backfire. As the saying goes:</p><blockquote>Time in the market beats timing the market</blockquote><p>The market has historically been bullish on average. And we can safely assume that it will mostly continue to grow for many reasons, including the simple one that governments continue to inflate the total supply of FIAT money. The M2 supply of USD grew from $280 billion to $ 22 trillion — a whooping 80 times, from 1960 to today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*3hSLU5QBZ_PiER0_.png" /></figure><p>I have 1 question to the bears — do you expect governments to stop printing money?</p><p>Thank you for reading my newsletter! I am not a financial advisor, none of this is financial advice, and should be used only for education purposes. Please subscribe to receive my future posts directly to your email at <a href="https://atomicknowledge.substack.com/">https://atomicknowledge.substack.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31cac07d61f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the Half-Life of Death?]]></title>
            <link>https://medium.com/@erdavtyan/what-is-the-half-life-of-death-101e56b0fc09?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/101e56b0fc09</guid>
            <category><![CDATA[estimations]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[puzzle]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Sat, 03 May 2025 11:24:01 GMT</pubDate>
            <atom:updated>2025-05-03T11:24:01.653Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fun Math</h4><h4>The Unreasonable Effectiveness of Estimation Problems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Px7QwGzJhrsilh7u" /><figcaption>Photo by <a href="https://unsplash.com/@varpap?utm_source=medium&amp;utm_medium=referral">Vardan Papikyan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Problem</h4><p>Solving a puzzle feels good, because in the end you see a result which is both elegant and rewarding. Knowing how to solve puzzles helps in real life situation as well — you can break down large problems into small ones, and tackle each one as a small and clever puzzle piece. This is why interviewers often ask logical puzzles, like the famous Google interview question “how many windows are in New York City?”</p><p>When discussing the pandemic, my sister asked me a simple question — how many people die in a second. I could have Google searched or asked ChatGPT, but I took the question as an estimation puzzle, a morbid version of the aforementioned Google interview question. If we are able to estimate the number of people who die in 1 second, we can take it a step further and estimate the human life expectancy as well. Please take a moment to think about the problem for yourself before reading my solution.</p><h4>The Method</h4><p>I decided to go with the population delta route. I remember around 20 years ago when I heard that humanity has reached a population of 7 billion, and only recently it reached 8 billion. This led me to my first assumption — let’s say humanity grows by 1 billion people every ~20 years. Secondly, while researching some population graphs a few years ago, I noticed that the number of people born are, on average, 2 times more than people who die. Coupling this with the previous assumption, I concluded that in 20 years 2 billion people are born, and 1 billion people die, resulting in a total growth of 1 billion people.</p><blockquote>I assume the global population grows by 1 billion people every 20 years and birth-to-death ratio is 2</blockquote><h4>The Calculation</h4><p>If 1 billion people die in 20 years, then 50 million people die in 1 year.</p><blockquote>1,000,000,000 / 20 years = 50,000,000 deaths/year.</blockquote><p>1 day has 86.400 seconds, let’s round it to 100.000 for simplicity. A year has 365 days, which I similarly rounded up to 400. This resulted in ~40 million seconds per year.</p><blockquote>50.000.000 deaths / 40.000.000 seconds = 1.25 deaths / second</blockquote><p>However, as I rounded the denominator up twice (86400 -&gt; 100k, 365 -&gt; 400), the result I got is smaller than the real number. We can safely round up the result to get ~2 deaths / second. Feel free to check the result of the estimation by Googling it, but I have a second estimation trick up my sleeve.</p><h4>The Half-Life of Death</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oZxQTPpbyucoWiGz" /><figcaption>Photo by <a href="https://unsplash.com/@mathieustern?utm_source=medium&amp;utm_medium=referral">Mathieu Stern</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I decided to take this a step further and calculate the number of seconds it would take for a person to have a 50% chance of dying. It is worth mentioning that this estimation does not take into account age, sickness, or any other factor correlated with death — we consider all people equivalent, and only use the result from the previous estimation step.</p><p>There are 8 billion people, and 2 people die per second — so the chance than an average person will die at any particular second is 2 / 8 billion = 1 / 4 billion.</p><blockquote><strong>Instantaneous death rate</strong> per person per second</blockquote><blockquote>λ = 2 / 8 000 000 000 = 1 / 4 000 000 000</blockquote><p>So the chance of surviving for 1 second is (1 — λ)</p><blockquote>(1 — λ) = 3 999 999 999 / 4 000 000 000</blockquote><p>As every second is equivalent to every other second, the chance that a person will survive X seconds is (1 — λ)^X. Thus, to get the number of seconds during which a person has 50% chance of survival, we need to solve for X the equation.</p><blockquote>(1 — λ) ^ X = 0.5</blockquote><p>So, we need to solve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJwskef2TmpAoVjrj7itrw.png" /></figure><p>Using a calculator and substituting 3 999 999 999 for (1- λ), we get X = 2772588492 seconds = 87.9 years.</p><p>According to our estimations, the half-life of death is 87.9 years. Considering the number of time we made assumptions, rounded numbers up and down, and made estimations — this result is surprisingly close to the actual global average life expectancy, highlighting the <strong>unreasonable effectiveness of estimation problems</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=101e56b0fc09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Illusions of Perceived Reality]]></title>
            <link>https://medium.com/@erdavtyan/illusions-of-perceived-reality-ab5aac9561b2?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5aac9561b2</guid>
            <category><![CDATA[universe]]></category>
            <category><![CDATA[existentialism]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 08:08:03 GMT</pubDate>
            <atom:updated>2025-09-01T17:52:33.515Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reflections from the Edge</h4><p>The universe looks particularly orderly today. With most of the size and speed spectrum covered with classical, relativistic, and quantum physics, we are well on our way to describe this magnificent medium we live in. However, there are a few problems.</p><p>Humans have 5 senses. They allow us to see, hear, taste, smell, and touch, and these 5 were apparently the best adaptations evolutionarily. However, 5 is an arbitrary number, and there can, and most likely do exist many phenomena which we can’t perceive at all. You could imagine the universe as a massive well of bursting activity that would take a billion-sense organism to fully grasp. That complexity gets projected onto the plane of our 5 senses, and that minuscule projection is what we perceive and recognize. If this idea sounds too abstract, remember that we can never feel gravitational waves passing though us, and only discovered them due to the creativity and ingenuity of scientists. Couple that with our cluelessness surrounding dark matter and dark energy, and it becomes clear that the universe is too vast our ever-expanding understanding is still very limited. Who is to say these are the last imperceivable things we will ever discover? And who is to say how many of those phenomena are perpendicular to our 5-plane perception, with their projection being an undetectable point? To make things more challenging, we don’t even perceive those 5 fully. We can only see visible light, which is a tiny part of the electromagnetic spectrum, and hear a particular range of vibrations.</p><figure><img alt="A human figure standing in the vastness of the universe" src="https://cdn-images-1.medium.com/max/1024/1*pmRUFBLDFtbqGhtZ1nIceQ.jpeg" /></figure><p>This is not the end of the story. The 5 senses that evolved through evolution don’t tell us the proverbial “truth” about the world surrounding us. They tell us whatever is best for us to hear to survive and reproduce. When our ancestors saw movement in the bushes, they had the choice to assume it to be a tiger or a rabbit. As it was indeed a tiger sometimes, the ones who assumed it’s a tiger survived a tiny bit more often. Over millions of years, that difference compounded, and we come from those ancestors. This limitation is good if you live in the forest and try to survive for a few years longer, but not helpful whatsoever if you want to see the true colors of the universe. Of course the scientific method is useful in fighting these limitations and biases, but there are many examples of the biases sneaking in, detected only years later.</p><blockquote>In our everyday lives, we only see a 5-dimensional projection of whatever is out there, and the projections are limited by the physical attributes of our receptor organs, and distorted by our ancestors’ need to survive and reproduce.</blockquote><p>Given our history of relentless pursuit and curiosity — taking over seas and moons alike — I hope we will uncover more dimensions and arrive at an elegant description of what is truly going on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5aac9561b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting highly scalable serverless Telegram bots]]></title>
            <link>https://medium.com/@erdavtyan/architecting-highly-scalable-serverless-telegram-bots-5da2bb8fab61?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5da2bb8fab61</guid>
            <category><![CDATA[sst]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 20:02:41 GMT</pubDate>
            <atom:updated>2024-03-03T20:13:26.832Z</atom:updated>
            <content:encoded><![CDATA[<h4>Test hundreds of bots without spending a dime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VeuezFWiujzX-t0E" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Telegram as a store</h4><p>Telegram is an under-appreciated application store. It has a large active userbase, and a great API with large file uploads, payments, and many other useful functions. You get a battle-tested, multi-functional chatting app frontend for free, all you have to do is provide value to its users. Even <a href="https://twitter.com/levelsio">levelsio</a>, one of the most prolific solopreneurs, migrated his community to Telegram and is building his latest startup as a Telegram bot.</p><h4>Hosting Telegram bots</h4><p>So building Telegram bots is a good idea, but how can we deploy it? As we aim to build a validate many ideas, our deployment options need to satisfy a few basic requirements:</p><p>1. Be low cost, preferably free until they hit virality<br>2. Allow us to create many different bots to try them out at once<br>3. Allow frictionless development, with infrastructure that does not get in our way<br>4. Be massively scalable, if we do hit virality</p><p>The method that best satisfies all these requirements is AWS serverless offerings. We can deploy our bot as an AWS Lambda, and only pay for the compute time. This time, even if we simultaneously test out hundreds of different bots, we won’t be charged unless the bots are actually being used. AWS provides a generous free tier — each month you get 1 million invocations of Lambda, and 400,000 GB-second of compute time for free. Hitting these limits means your bot is actively being used, which is an excellent problem to have.</p><h4>Leveraging Infrastructure as Code</h4><p>Setting up AWS resources manually can be time-consuming, and error-prone. One way around this is to use Infrastructure as Code principles. We can declaratively specify the resources we want to use in code. Then, we can commit the code into a repository. Thus our infrastructure will be version-controlled and repeatable. If something goes wrong you can easily revert the change. If you need another environment like staging, you can repeatably deploy the exact same infrastructure again.</p><p>However, there are levels to Infrastructure as Code. The first level is to version control your infra and make it repeatable. But it is detached from your actual code and lives and evolves separately. Usually, even in companies that utilize IaC, deploying new resources is still tedious and annoying. True IaC is when infrastructure is a first-class citizen in your code and spinning up a lambda is as easy as adding a new route to your express app.</p><h3>SST</h3><p>SST solves the exact problem I described above. It allows you to deploy many types of serverless offerings — including Lambdas, SQS queues, EventBridge buses, databases, S3 buckets, and more. And it does this in a way that does not get in your way, but instead helps you achieve your goals faster. We will use SST for our Telegram bot-building meta-framework.</p><h4>Setup an SST app</h4><p>SST has an excellent [guide](<a href="https://sst.dev/guide.html">https://sst.dev/guide.html</a>) to help you get started with the basics of IaC and SST. Following the steps from the guide and their docs, we can set up an SST app using this snippet. Feel free to use whatever package manager you like best, I use `pnpm` as it closely matches our goal of deploying many Telegram apps without them taking too much space.</p><pre>pnpm create sst telegram-bot<br>cd telegram-bot<br>pnpm install</pre><p>The default app, as of the writing of this article, has an Event Bus and 3 Lambdas configured out of the box. We won’t need most of these. Feel free to delete the EventBus construct from `stacks/MyStack.ts` and remove the 2 `/todo` endpoints passed to the Api construct. Make sure you have a configured AWS account. If you don’t, you can follow the SST guide to get everything you need. Then, run</p><pre>pnpm sst dev — stage dev</pre><p>This will set up an AWS environment with the name `dev`, and deploy all the necessary CloudFormation and adjacent resources on which SST depends. Afterwards, the magic of SST begins — you will get a “live” Lambda function which will rebuild whenever you change the code. This is great because you get to test your app directly against the infrastructure you will be using in the future. It’s amazingly fast as well!</p><p>You can curl the url outputted in your terminal and you will get a Hello World response. Congratulations! You set up your massively scalable AWS Lambda deployment, spending little to no time to get most of the sensible best-practice defaults.</p><h4>Setup Telegram bot with BotFather</h4><p>Now that we have our deployment environment, we need to set up our bot. Telegram has a bot to rule them all, with an offer you can’t refuse — the <a href="http://twitter.com/BotFather">@BotFather</a>. Search for this username in the Telegram search bar, and follow the straightforward directions to register your bot. Take note of the token it gives you, as that token is what we will use to control the bot.</p><h4>Telegraf</h4><p>There are [many bot libraries](<a href="https://core.telegram.org/bots/samples">https://core.telegram.org/bots/samples</a>) for Telegram, and the one we will use in this guide is [Telegraf](<a href="https://github.com/telegraf/telegraf">https://github.com/telegraf/telegraf</a>). This library allows us to use Telegram bot features in TypeScript. Install this library in the `packages/functions` directory of your app.</p><pre>cd packages/functions<br>pnpm add telegraf</pre><p>Now we can use Telegraf to create a convenient interface to the Telegram API.</p><pre>const bot = new Telegraf(“123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ”);</pre><p>But wait a second! We can’t just leave our bot token in code in plaintext. Fortunately, SST has a great way of handling secrets. Let’s set up an SST secret. This command will create an object in ParameterStore and encrypt it with a key from KMS.</p><pre>pnpm sst secrets set TELEGRAM_BOT_TOKEN “123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ” — stage dev</pre><p>Now, let’s add the secret to our stack.</p><pre>const TELEGRAM_BOT_TOKEN = new Config.Secret(stack, “TELEGRAM_BOT_TOKEN”);</pre><p>Don’t forget to import the Config construct and bind it to the API like so.</p><pre>import { StackContext, Api, Config } from “sst/constructs”;<br><br>...<br><br>const webhook = new Api(stack, &quot;api&quot;, {<br>  routes: {<br>    &quot;POST /&quot;: &quot;packages/functions/src/lambda.handler&quot;,<br>  },<br>  defaults: {<br>    function: {<br>      bind: [TELEGRAM_BOT_TOKEN],<br>    },<br>   },<br>});</pre><p>We can now easily use the secret in our lambda function.</p><pre>import { Config } from “sst/node/config”;<br><br>...<br><br>const bot = new Telegraf(Config.TELEGRAM_BOT_TOKEN);</pre><p>Let’s set up a simple command to say `Hello` to all users who “start” our bot.</p><pre>bot.start((ctx) =&gt; ctx.reply(“Hello”));</pre><p>Okay now that we have the bot set up, we should just call `bot.launch()`, right? Well, not quite.</p><h4>Polling vs Webhook</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*24HQzbWLn1w1U3S8" /><figcaption>Photo by <a href="https://unsplash.com/@stevehb?utm_source=medium&amp;utm_medium=referral">Steve Houghton-Burnett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are 2 ways of setting up Telegram bots — polling, and webhooks.</p><p>The easy method is to use Polling. This means your app periodically queries Telegram for new messages. This is super easy to set up in a server and works great for bots that don’t have scalability requirements. However, we do not have a server, and we do want scalability.</p><p>So, our solution is to use Webhooks. You specify an endpoint, and Telegram sends a request to that URL whenever a new message comes in. With this method, your bot can “sleep” when it’s not in use. This means we can safely let the Lambda turn off and not worry about missing any messages. Whenever our users message us, the Lambda will wake up, handle that one message, and go back to sleep.</p><p>Instead of launching the bot or attaching it to an existing server, we can manually handle incoming messages using the `bot.handleUpdate` method.</p><pre>const update = JSON.parse(_evt.body);<br>await bot.handleUpdate(update);<br>return { statusCode: 200, body: “” };</pre><p>The last step is to let Telegram know about the endpoint of our webhook. This is, of course, possible to do programmatically. But as it’s a one-time call, I find it easier to just `curl` the command directly.</p><pre>curl https://api.telegram.org/bot{bot_token}/setWebhook?url={lambda_url}</pre><p>And that’s that! Now you can send the `/start` command to your bot and get back a message.</p><h4>Pitfalls and Edge Cases</h4><p>Unfortunately, the bot is not ready yet. There are still changes we need to make to handle messages in a more semantically correct way. For an example of a common pitfall, we can change the bot response computation to take more time. We can send a request to an external API like OpenAI and reply with the AI’s response. In some cases, the webhook will time out, and Telegram will re-send the original message. To handle this, we need a more robust infrastructure and a better strategy of handling messages.</p><p>Telegram expects a response from our webhook. If we do our calculations and return the response too late, it times out and retries. A naive strategy might be to always respond immediately, and only then handle the message. This can be easily achieved by removing the `await` from `bot.handleUpdate()` call. However, this leads to message ordering issues. Telegram delivers messages in order and only delivers the next message once you acknowledge the receipt of the previous one by responding to the webhook call. So, if you always respond early and then handle the messages, you will get all the messages at the same time, which will inevitably result in race conditions, ordering issues, and parallelism where we don’t want it. To avoid data loss and corruption, we need to design a strategy to handle the messages in order, but without timing out.</p><h4>SQS Queue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wHYXo33_8fu0KmY-" /><figcaption>Photo by <a href="https://unsplash.com/@meizhilang?utm_source=medium&amp;utm_medium=referral">Meizhi Lang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The semantically correct way to achieve this is to use SQS Queues. We could also use EventBridge, but Events don’t guarantee ordering, while SQS queues do. So, in our architecture, we can `Get a message to the webhook` -&gt; `Add the message to a queue` -&gt; `Respond to the webhook request`. And with another Lambda function, we can handle the messages from the queue. In this case, we could still have issues of responding in time, because of unexpected intermittent network failures. But we can simply use a `DeduplicationId` for each queue message to make sure we handle every Telegram update only once.</p><p>This strategy is not foolproof — at least not yet. If we have 100 users using our bot simultaneously, and we push all their messages into a queue, the users will block each other. Our Lambda will handle the messages one by one, and the users who send their messages later will need to wait until all others are handled. This is not what we want — we essentially want to have one queue per user. SQS queues have an excellent way of handling this — FIFO queues with `MessageGroupId`s. We can push messages into the queue and set the userId of the sender as the `MessageGroupId`, and this will be exactly what we need.</p><p>Add this snippet of code to set up the queue in the stack.</p><pre>const messageQueue = new Queue(stack, “messageQueue”, {<br>  cdk: {<br>    queue: {<br>      fifo: true,<br>    },<br>  },<br>  consumer: {<br>   function: {<br>     bind: [TELEGRAM_BOT_TOKEN],<br>     handler: “packages/functions/src/messageConsumer.handler”,<br>   },<br>  },<br>});</pre><p>And make sure to bind the queue to the webhook, to make sure it has the necessary permissions to push to the queue. Also notice that we remove the TELEGRAM_BOT_TOKEN binding, as the webhook will no longer need to talk to Telegram. It will only be used to push messages to the queue and respond to the Telegram API with a 200 status code.</p><pre>const webhook = new Api(stack, “api”, {<br>  routes: {<br>    “POST /”: “packages/functions/src/webhook.handler”,<br>  },<br>  defaults: {<br>    function: {<br>      bind: [messageQueue],<br>    },<br>  },<br>});</pre><p>In the `webhook.ts` file, change the `handler` function.</p><pre>const sqs = new SQSClient({});<br><br>export const handler = ApiHandler(async (\_evt) =&gt; {<br>  const update = JSON.parse(\_evt.body);<br>  const messageId: string = `${update.message.message_id}`;<br>  const userId: string = `${update.message.from.id}`;<br><br>  const command = new SendMessageCommand({<br>    QueueUrl: Queue.messageQueue.queueUrl,<br>    MessageBody: _evt.body,<br>    MessageDeduplicationId: messageId,<br>    MessageGroupId: userId,<br>  });<br><br>  await sqs.send(command);<br><br>  return { statusCode: 200 };<br>});</pre><p>And create a `packages/functions/src/messageConsumer.ts` file with this `handler` function in it.</p><pre>import { SQSEvent } from “aws-lambda”;<br><br>export const handler = async (_evt: SQSEvent) =&gt; {<br>  const bot = new Telegraf(Config.TELEGRAM_BOT_TOKEN);<br>  bot.start((ctx) =&gt; ctx.reply(&quot;Hello&quot;));<br>  for (const record of _evt.Records) {<br>    const update = JSON.parse(record.body);<br>    await bot.handleUpdate(update);<br>  }<br><br>  return {};<br>};</pre><p>Make sure to handle the necessary package installations in `packages/functions`.</p><pre>pnpm add aws-lambda</pre><h4>Conclusion</h4><p>And that’s it! We have added a queue to our infrastructure and push all incoming messages to it. This way, we can quickly respond to the Telegram API, while still making sure we keep the ordering of the messages coming in. Also, we parallelize the handling of messages for multiple users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5da2bb8fab61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using ChatGPT for Writing]]></title>
            <link>https://medium.com/@erdavtyan/dont-use-chatgpt-for-writing-c7060c0b4115?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7060c0b4115</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 12:23:36 GMT</pubDate>
            <atom:updated>2024-01-20T05:12:10.287Z</atom:updated>
            <content:encoded><![CDATA[<h4>ChatGPT Anti-tutorial</h4><h4>This article was written without the use of AI.</h4><p>I love writing. I love it in many flavors — be it research or policy papers, technical tutorials, or standup comedy material. The process of writing and research is exciting — hopping through multiple sites and learning about new perspectives helps me dive deeper into the topic.</p><p>But it is also time-consuming and frankly — <strong>hard</strong>. I often don’t like some part of my writing, or can’t find the right analogy to explain my point. I take multiple days of writing and rewriting, editing and reordering, to get to a point where I am happy with the result.</p><blockquote><strong>Plays are not written — they are rewritten. — </strong>Steele MacKaye</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sk_scxkJRyPkBpBK" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=medium&amp;utm_medium=referral">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So when ChatGPT 3.5 was released, and I saw the incredible potential of the tool— my productivity-focused mind jumped at the opportunity. I decided to “recruit” my AI friend to write more and better articles. And it worked… almost.</p><p>The journey wasn’t without hiccups. It quickly became apparent how much work I needed to put into prompting and reprompting, guiding the AI to talk more about a certain aspect of the topic, and making sure it didn’t get off track. I discovered and learned many prompting techniques. One of my favorites is choosing a somewhat broad topic, and asking ChatGPT to list 10 titles for articles about that topic. Asking the AI to “list” something forces it to flex its creativity muscles. You might be surprised with what it can come up with.</p><p>Initially, it was hard to write well-researched articles, because the AI had a knowledge cut-off. Articles about recent events, or devices and tech which came out not too long ago were impossible to write. But this was also fixed with the release of GPT-4 and its ability to browse the web using Bing. If you asked me which search engine I predict an AI would use, Bing would not be in my top 10. I often wonder how we don’t get unhinged hallucinations from the searches.</p><p>After some time I got familiar with using the AI. I used prompting techniques to list topics, then picked one of them and asked it to “research and write an introduction for an article”. This let the AI know that it should leave space to continue the article, not just put everything in a short message. Depending on the result I would then guide it to write body paragraphs, come up with analogies, write some jokes here and there, and conclude with a hard opinion instead of a wishy-washy “all options are great”.</p><p>If you do end up using ChatGPT for writing, I recommend playing around and discovering the prompting techniques that work best for you. You should also check out the official <a href="https://platform.openai.com/docs/guides/prompt-engineering/prompt-engineering">Prompt Engineering Guide</a> from OpenAI. Of course, use the newest model (GPT-4 at the time of writing), and take a look at the multitude of <a href="https://chat.openai.com/gpts">custom GPTs</a> created specifically to help you write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*YP5fRXxR73Z5slVAME5weg.png" /></figure><p>Using AI for writing was a superpower. It was fast. I felt like I was learning a lot by reading the output and managing it. However, just like with every other “silver bullet”, cracks started forming in my process over time. As I got better at prompting and getting it to write something I liked, I started paying less attention to the output. Instead of reading it thoroughly, editing it, and incorporating my personality into the writing, I was only lightly skimming the results. On multiple occasions, I considered fully automating the process of writing by algorithmically walking through listing -&gt; writing an intro -&gt; writing body paragraphs 1, 2, 3 -&gt; writing an outro -&gt; publishing to a blog .</p><p>I also recognized that the feeling of learning was fake. If you take a math class and you see your instructor solve a complex problem, you might think you understand the solution. But that doesn’t mean you can solve it yourself. It takes deliberate effort, multiple tries and failures, and progressive overload with harder problems of a similar type to truly “learn” anything. And that was lacking with the AI — it just presented the finished answers, and my gullible brain thought I was learning.</p><p>Over time, I lost my passion for writing. I realized, that just like journaling — the point of writing is in the process, not the outcome. I hope we won’t come to a day when people use AI to journal. It sounds ridiculous now, but it might be less ridiculous when we see bigger and better models come out which can help us “get our minds on paper” easier. Of course, I think that approach misses the purpose of journaling. And so does using AI for writing.</p><p>Outside of personal reasons, there are a lot of collective reasons to write without AI as well. AI models are essentially large databases — paraphrasing what has already been said thousands of times before. Using it often creates a monotonous tone, repeated content, and does not increase the amount of information on the web. It kills your personality and creative voice, turning your writing into yet-another-AI-blog.</p><p>I have decided to take a step back. I wrote this article without any use from AI assistants. I structured it myself and wrote the analogies and the jokes too. It took more time, but as expected, I enjoyed the process more. In our increasingly AI-flooded blog scene, I am hoping that writing myself will increase the quality of my articles again, making them unique, and most importantly — making the process fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7060c0b4115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Never Get a Job]]></title>
            <link>https://medium.com/@erdavtyan/how-to-never-get-a-job-a1509fd333d8?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1509fd333d8</guid>
            <category><![CDATA[work]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[layoffs]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Tue, 23 May 2023 21:14:28 GMT</pubDate>
            <atom:updated>2023-06-13T19:18:31.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*giW6u6LxS9r6jvrG" /><figcaption>Photo by <a href="https://unsplash.com/@martenbjork?utm_source=medium&amp;utm_medium=referral">Marten Bjork</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you have that one coding skill, and you are really good at it. And you say you want to get a job. You say you want to improve your skills and become a better programmer. But your actions tell me otherwise, and actions always speak louder than words.</p><p>As we are entering a more complex financial environment and companies are laying a lot of people off, it has never been easier to lose your job or be unable to get a new one. In this article I want to present to you a step-by-step approach to guarantee that you won’t get a new job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sxke93u6ladbC4Zg" /><figcaption>Photo by <a href="https://unsplash.com/@emkal?utm_source=medium&amp;utm_medium=referral">Emil Kalibradov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“It has never been easier to lose your job or be unable to get a new one”</blockquote><h4><strong>Always stick to your current tools</strong></h4><p>Be overconfident in your skills. You know enough. Have you learned JQuery in 2017? That’s great! It gets the job done and maybe you were even able to make a few portfolio websites back then. Why would you waste your time learning new technologies if the tool you already know works just fine? Sure, it creates less maintainable code in the end, isn’t as modular, doesn’t fit the architecture of more complex modern applications — but it works Also it’s not like the other tools like React or Vue don’t have their own problems, and why would you add problems to your life?</p><h4><strong>Don’t switch up paradigms</strong></h4><p>You are a frontend developer at heart, and nothing should force you to look at backend code. Don’t worry, the recession will end, ChatGPT will be shut down, and your skills of designing beautiful browser boxes will stay relevant forever. Don’t look into other aspects of programming like backend or devops or security. You don’t need that extra work time that you could instead spend on the latest Netflix series.</p><h4><strong>Wait for job offers come to you</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AngycTp-VHGhNjP-" /><figcaption>Photo by <a href="https://unsplash.com/@hannahbusing?utm_source=medium&amp;utm_medium=referral">Hannah Busing</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s admit it — applying to jobs is hard. You need to maintain an always-updating resume, search for companies, go through interviews, and probably get rejected from some of them. All this is stress. Why bother applying for jobs when you can just sit back, relax, and wait for offers to come to you? I recommend you avoid all job search websites and don’t bother networking. Keep irrational hope that a job offer falls into your lap without any effort on your part.</p><h4><strong>Give up easily</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s19jl9DXphhdnfHP" /><figcaption>Photo by <a href="https://unsplash.com/@davfts?utm_source=medium&amp;utm_medium=referral">David Pupăză</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the rare case that a job offer <em>does</em> come to you in some miracle way, it’s important to keep this one crucial step in mind. Whether it’s during the technical interview or the take-home task — if you ever feel stuck — give up. It’s not like they are paying you for it anyway. And the actual job pay was probably gonna be too low. Make up any other excuse you find fitting, and just get back to your own super-interesting stress-free life. This opportunity came from nowhere, so probably a lot more will come.</p><h4><strong>Never challenge yourself with coding projects</strong></h4><p>Programming is a job, it isn’t a hobby. Use your free time for stuff that’s less labor-intensive. Play video games, watch TV, and daydream about the future. You’re gonna code a lot in your future career anyway, so why bother now? <br>Don’t even try to contribute to Open Source. FOSS is a scam. You shouldn’t code for other people for free. Just use what the open source community creates and never give back.</p><h4><strong>Stay on the surface</strong></h4><p>Don’t bother with the intricacies of the tools you are using. Why would you learn how React works under the hood, or how TCP handshakes work? Who cares how your Language Server communicates with your editor? Treat all of these as a black box and never look deeply into it. If it ever breaks, it’s not your problem — it’s the problem of the person who made it in the first place. Going back to the first point — stick to the tools you know, including your editor. Vim or Emacs or these other extensible customizable editors are a nerdy waste of time — you’re better than that.</p><h4><strong>Ignore the benefits of content creation</strong></h4><p>On the topic of never giving back, you shouldn’t educate others either. You are really good at what you do so you should guard your secrets. So why waste your time creating content like blog posts, tutorials? Don’t bother contributing to the community or building your personal brand. Ignore the fact that content creation can lead to professional opportunities and help establish your expertise in the industry. Remember, staying in your comfort zone and never sharing your knowledge is the secret of staying ahead of the curve.</p><h4><strong>Avoid professional development opportunities</strong></h4><p>By this time you are almost guaranteed to not get a job. But just to put the nail in the coffin you should avoid all professional development opportunities. This includes networking, making friends who are also programmers, and participating in hackathons. You should also ignore any programming content in the internet like courses or free YouTube videos. Don’t bother participating in anything that could potentially enhance your skills, knowledge, or brand image.</p><p>At the end of the article I wanna remind you that life is short. You are not always going to have a <strong>tomorrow</strong>. Enjoy today, make sure you spend as much time as possible not working. Get out of bad late in the day, never exercise, scroll social media.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MyEMEU5QKA75vyYZ" /><figcaption>Photo by <a href="https://unsplash.com/@lidyanada?utm_source=medium&amp;utm_medium=referral">Lidya Nada</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Make maximizing your instant gratification dopamine levels your highest priority. Dopamine is the happiness drug, so maximizing it is the secret to eternal happiness.</blockquote><p>If you enjoyed this article you can find its accompanying <a href="https://www.youtube.com/watch?v=UHWmCMfpQlY">video in YouTube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1509fd333d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling global state in React without Providers and boilerplate]]></title>
            <link>https://itnext.io/handling-global-state-in-react-without-providers-and-boilerplate-61d9b371bc14?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d9b371bc14</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Sat, 09 Oct 2021 09:51:37 GMT</pubDate>
            <atom:updated>2022-05-17T17:37:38.468Z</atom:updated>
            <content:encoded><![CDATA[<p>ReactJS has a built-in way to handle “global” state — React Context. However, after using many contexts I realized I am typing a lot of boilerplate code and getting to a “Provider hell”. I had to nest Provider after Provider in my root App component to ensure that all the children had access to it. For a simple example — let’s construct a toggleable theme context. First, we need to create the type of the context (this article assumes usage of typescript). Let’s have the type be similar to the return value of useState — so [theme, setTheme]. Then, we need to create the context, and pass it an initial value. The second (setTheme) element of the tuple is unnecessary, but we still have to do it. Then we need to create the provider, which takes children as props and passes them down the tree, while creating the theme and passing it to the ThemeContext.Provider component. The entire code of that file looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QM6wXg2BmmPvpJAxAzlK3w.png" /><figcaption>Implementing theme using context API</figcaption></figure><p>Then we have to go to a component close to the root of our tree and add the Provider there, next to many other providers (if the project is big enough).</p><p>Facing the need of “state-like” contexts, I decided to give it a different solution. I built a createStateHook function which keeps the state in a closure and returns a hook that uses that state and rerenders when the state changes. I used the “magic” of rxjs for this to make the code shorter, but it’s entirely possible without using rxjs dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sGw9KN-TqZCMd3UU" /><figcaption>createStateHook implementation</figcaption></figure><p>Now we can create the theme in a much easier way. We only need the type of the theme, and to call the createStateHook function with the initial value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jdGju2bL9_oEN3aN" /><figcaption>Global theme with createStateHook</figcaption></figure><p>There is no need to add a provider at a higher level. useTheme hook will work anywhere, and when the theme is changed — all the components that use useTheme will be rerendered.</p><p>For global values that resemble the shape of “state” (which is a lot of them), this approach is far more concise. We converted code from ~20 lines + a Provider in the root component to 2 lines without a provider.</p><p>You can follow more awesome tips that I post on <a href="https://blog.erikdavtyan.com/">blog.erikdavtyan.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d9b371bc14" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/handling-global-state-in-react-without-providers-and-boilerplate-61d9b371bc14">Handling global state in React without Providers and boilerplate</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React state management library with built in effects support]]></title>
            <link>https://itnext.io/building-a-react-state-management-library-with-built-in-effects-support-36c5f5358dc2?source=rss-39b28d4369b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c5f5358dc2</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Erik Davtyan]]></dc:creator>
            <pubDate>Mon, 04 Oct 2021 13:14:37 GMT</pubDate>
            <atom:updated>2021-10-05T17:33:53.488Z</atom:updated>
            <content:encoded><![CDATA[<p>While building a chat business logic library for react, I realized that the current state management solutions are lacking. Chat is a real-time complex app with many listeners — you have to make sure to have a callback when I join a new chat room, make sure to listen to new messages and read indicators in every room, make sure to listen when a participant changes their profile picture. When people talk about state management libraries, they always talk about how it is non-trivial to handle fetch and other Promise-based async operations in them. But it is significantly harder to handle event-based asyncronosities, and to clean up after yourself not to leave any memory leaks. The best solution we have right now is redux-observables, which is a very elegant way to solve these issues, but I believe it can be done in a simpler way. Facing this issue I decided to try to build my own state management solution, starting from scratch and solving my problems as I go.</p><p>You can find the finished library here — <a href="https://www.npmjs.com/package/@plancky/state">https://www.npmjs.com/package/@plancky/state</a>.</p><p>Firstly, I made a class that stores data and is able to communicate with the view layer when it changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88PGvE1KQAOBNa7tdAdK7A.png" /><figcaption>Notifier class</figcaption></figure><p>Now any class that extends from it can have internal data, methods to modify it, and call <strong>this.notify()</strong> whenever the view layer should be made aware of the changes. We can then subscribe to it from the view layer and rerender when <strong>notify</strong> is called, like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3z9LK-pGlugmWulyEXp3Xw.png" /></figure><p>Here is an example usage of the notifier class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njckR8rSIqxYpepJIirJAQ.png" /></figure><p>It is cumbersome to remember to call <strong>this.notify() </strong>every time a change occurs, so I decided to make a more idiomatic way of updating it — a StatefulNotifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wK-bdu_Wur5tyq-tceVxoQ.png" /></figure><p>This class not only informs the view layer when data changes, but implements a setState function similar to React’s setState, which calls <strong>notifiy() </strong>internally. Now we can extend from StatefulNotifier, pass our initial state and just use setState and not worry about remembering to call notify on every change.</p><p>We can wrap the creation of a StatefulNotifier into a function <strong>createStore() </strong>to make it easier to work with. It will take the initial state as the first argument, and a function to create the actions as a second argument. I took inspiration for this decision from the <a href="https://github.com/pmndrs/zustand">Zustand</a> state management library. At this point we have an api similar in essence to Zustand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_SjyOqzhQeBgEtfuPqTaQ.png" /></figure><p>And we can also create a simple <strong>useStore(store, selector) </strong>hook to use it in react and avoid unnecessary rerenders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBOgrpUO17KTB_Ag57MGxw.png" /></figure><p>Now we can create a store like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz_58B_BBsJo7ZOtJHJB5w.png" /></figure><p>Now, in our react layer, we can simply call</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM9TlXwHwmpP90G8S8Ou3Q.png" /></figure><p>And it takes care of rerenders when rooms changes automatically. We can also use any of the actions from our view layer.</p><p>Now we have a full-fledged state management solution for React. However, it is still cumbersome to handle events. Let’s say we want to add an event listener for new messages every time we call actions.addRoom(). Sure, we can start the effect in the actiona and have the action return an <strong>unsubscribe. </strong>But if we ever need to remove that room, we have to make sure we have a reference to that unsubscribe function. Also, when we call actions.removeRoom() we have to also remember to call that unsubscribe to avoid memory leaks. This is not reactive and bugs will certainly arise. Ideally — we want our state manager to handle this for us. We want it to add the event listener in <strong>addRoom()</strong> and remove it in <strong>removeRoom()</strong>.</p><blockquote>Effect is a function that starts some kind of process (e.g. event listener) and returns a cleanup. A great example of this is React’s useEffect hook.</blockquote><p>Being faced with this issue I dediced to implement support for adding and removing effects with ids in the store itself. The implementation of EffectiveStatefulNotifier looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TJ2FWBNAXMr2iWhNk1RKg.png" /></figure><p>Now we can modify the createStore function to handle effects as well. We only need to modify the Api type like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gj4hdewrIyITEPxrgaW8rw.png" /></figure><p>The rest remains the same, except instead of <em>new StatefulNotifier(state) </em>we now call <em>new EffectiveStatefulNotifier(state).</em></p><p>Now our state management solution has native support for effects, and we can modify addRoom and removeRoom functions like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiYCrMdGmpVYExocsqMO-g.png" /></figure><p>In the react layer we can call actions.addRoom(‘id’) and then cleanup with actions.removeRoom(‘id’) without worrying about memory leaks — the store handles that for us :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c5f5358dc2" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-a-react-state-management-library-with-built-in-effects-support-36c5f5358dc2">Building a React state management library with built in effects support</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>