<?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"><channel><title><![CDATA[A techie's ramblings]]></title><description><![CDATA[Software engineer based in Singapore. Occasionally, I explore systems programming to satisfy my curiosity about the things further down the stack.]]></description><link>https://yaphc.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Nov 2026 03:00:35 GMT</lastBuildDate><atom:link href="https://yaphc.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Reverse engineering CoinMarketCap API]]></title><description><![CDATA[Dig into the NextJS bundle]]></description><link>https://yaphc.com/reverse-engineering-coinmarketcap-api</link><guid isPermaLink="true">https://yaphc.com/reverse-engineering-coinmarketcap-api</guid><category><![CDATA[reverse engineering]]></category><category><![CDATA[CoinMarketCap]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sat, 14 Jun 2025 14:36:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749909170755/49f31678-2c27-49da-a7c5-b501b706228c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Earlier, I <a target="_blank" href="https://yaphc.com/stocks-notification-tradingview-webhook-to-telegram">discussed</a> how to set up a TradingView webhook and send notifications to telegram for stocks.</p>
<p>The full workflow looks something like this:</p>
<ul>
<li><p>Before the market opens, send a telegram notification with stock data from TradingView, VIX Central, and CNN fear and greed index.</p>
</li>
<li><p>When the market closes, receive the TradingView webhook and save the data in Redis.</p>
</li>
</ul>
<h2 id="heading-crypto-telegram-notification-workflow">Crypto telegram notification workflow</h2>
<p>There is a similar workflow for crypto as well. Before the market opens, a telegram notification is sent with data from CoinMarketCap and the <a target="_blank" href="https://alternative.me/crypto/fear-and-greed-index/">alternative.me</a> fear and greed index. However, there is no TradingView webhook to receive data from.</p>
<h2 id="heading-locating-the-data">Locating the data</h2>
<p><em>Note: This post is for educational purpose only.</em></p>
<p>This is the <a target="_blank" href="https://coinmarketcap.com/cryptocurrency-category/">page</a> on CoinMarketCap where I found the data for the 24-hour price change by sectors.</p>
<p>This page is server-side rendered (SSR), so there is no API request for this data when you inspect the network tab.</p>
<p>CoinMarketCap uses NextJS, which stores the SSR data in <code>window.__NEXT_DATA__</code>, and the data we are interested in is located at <code>props.pageProps.data</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749476854115/ed00ab39-dd3c-4b3f-b1d7-db6482567441.png" alt class="image--center mx-auto" /></p>
<p>You can also find it in the page source.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749909694394/27f63029-51f8-4cd1-8220-e2f83eea275c.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-finding-the-api-request">Finding the API request</h2>
<p>Getting the data from HTML is fine, but having an API is better.</p>
<p>In Chrome's source tab, locate the Next.js bundle under the <code>s2.coinmarketcap.com/cmc/_next/static/chunks/pages</code> folder. There, you will find <code>_app**.js</code> and <code>cryptocurrency-category-**.js</code>.</p>
<p><code>_app**.js</code> contains the application-level code that is bundled for every page.</p>
<p><code>cryptocurrency-category-**.js</code> contains the code specific to this page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749478536712/d685b11a-8ab6-4fac-b571-f1e978173543.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-older-version-of-cryptocurrency-categoryjs">Older version of cryptocurrency-category**.js</h3>
<p>I still have an older copy of the JavaScript file for this page, which was retrieved sometime last year. The API call is found within a call to <code>F()</code>.</p>
<p><code>getInitialProps</code> is a NextJS lifecycle method that runs when the page is loaded.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749480427048/478bc2b0-034b-460a-944f-36a64d9c0fd6.png" alt class="image--center mx-auto" /></p>
<p>Clicking into the function reveals that the endpoint is at <code>/data-api/v3/sector/w/list</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749480624975/f4982430-62d3-45ff-8ff4-86f5196c3b60.png" alt class="image--center mx-auto" /></p>
<p>Requesting data from the endpoint gives the outdated version of the top sectors by 24-hour price change, which doesn't match what is shown on the page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749480886107/6957c379-ea69-47dc-b210-e7498002a226.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-current-version-of-cryptocurrency-categoryjs">Current version of cryptocurrency-category**.js</h3>
<p>With the updated version of <code>cryptocurrency-category**.js</code>, the API call is at <code>L()</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749481401975/e8a4a17e-d9d7-4bc3-a127-b305a762262c.png" alt class="image--center mx-auto" /></p>
<p>Clicking into the function reveals that the endpoint is <code>/data-api/v4/sector/m/full-list</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749481447099/21be38b2-46f5-4b8e-b3e9-842aa7755ab6.png" alt class="image--center mx-auto" /></p>
<p>Requesting data from the endpoint provides the current list of top sectors by 24-hour price change, which is displayed on the page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749481556728/12e7308d-3c63-437c-bf23-27c9585d07bf.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-api-domain">API domain</h3>
<p>The above 2 requests referenced the <code>javaApi</code> endpoint, which can be found in <code>_app**.js</code></p>
<h2 id="heading-tips">Tips</h2>
<p><strong>NextJS knowledge</strong></p>
<p>Since the page is written in NextJS, it's helpful to know where NextJS stores client-side data and understand the lifecycle method for fetching data.</p>
<p><strong>Trial and error</strong><br />Use the good old debugger to set a breakpoint, reload the page, and check if it gets triggered. If it does, there's a good chance it's the API request we're looking for.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749911390353/2ffe09b2-87a8-47bd-acc7-025a06f3cba6.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Stocks notification: Building multi-arch docker image]]></title><description><![CDATA[Bridging AMD64 and ARM64]]></description><link>https://yaphc.com/stocks-notification-building-multi-arch-docker-image</link><guid isPermaLink="true">https://yaphc.com/stocks-notification-building-multi-arch-docker-image</guid><category><![CDATA[multiarch]]></category><category><![CDATA[docker images]]></category><category><![CDATA[arm64]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 11 Aug 2024 09:51:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723369948505/ecc2f62d-143b-4eff-8439-86515e392ea4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Last year, around the same time, I added a feature in <a target="_blank" href="https://yaphc.com/stocks-notification-tradingview-webhook-to-telegram">market data notification</a> to scrape the stocks fear greed index from <a target="_blank" href="https://edition.cnn.com/markets/fear-and-greed">https://edition.cnn.com/markets/fear-and-greed</a>, with selenium and chrome webdriver.</p>
<h2 id="heading-difference-in-development-and-production"><strong>Difference in development and production</strong></h2>
<p>There is an issue: my development environment is on AMD64, while my production environment is on ARM64.</p>
<p>I switched from AWS T3 to T4g due to the superior price performance that the AWS graviton provides.</p>
<p>Previously, I used t3.micro, which has 2 vCPUs and 1GB of memory. However, 1GB was not enough because running Chrome and scraping the fear and greed data easily used up more than half of it, maxing out the available memory.</p>
<p>So, I searched and decided on t4g.small, which has 2 vCPUs and 2GB of memory.</p>
<h2 id="heading-changes-in-workflow">Changes in workflow</h2>
<p><strong>1. Multi-arch docker image for chrome</strong></p>
<p>Chrome is packaged for Ubuntu AMD64, not for ARM. Chromium is used for ARM instead.</p>
<p>A build argument <a target="_blank" href="https://docs.docker.com/build/building/multi-platform/">$TARGETPLATFORM</a> is available for this purpose.</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">RUN</span><span class="bash"> <span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$TARGETPLATFORM</span>"</span> = <span class="hljs-string">"linux/amd64"</span> ]; <span class="hljs-keyword">then</span> \
    wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - &amp;&amp; \
    <span class="hljs-built_in">echo</span> <span class="hljs-string">"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main"</span> &gt;&gt; /etc/apt/sources.list.d/google-chrome.list &amp;&amp; \
    apt update -y &amp;&amp; apt install -y google-chrome-stable; \
<span class="hljs-keyword">elif</span> [ <span class="hljs-string">"<span class="hljs-variable">$TARGETPLATFORM</span>"</span> = <span class="hljs-string">"linux/arm64"</span> ]; <span class="hljs-keyword">then</span> \
    wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/chromium-browser/1:85.0.4183.83-0ubuntu2.22.04.1/chromium-browser_85.0.4183.83-0ubuntu2.22.04.1.tar.xz &amp;&amp; \
    tar -xvf chromium-browser_85.0.4183.83-0ubuntu2.22.04.1.tar.xz &amp;&amp; \
    cp chromium-browser-85.0.4183.83/chromedriver /usr/<span class="hljs-built_in">local</span>/bin &amp;&amp; \
    cp chromium-browser-85.0.4183.83/chromium-browser /usr/<span class="hljs-built_in">local</span>/bin; \
<span class="hljs-keyword">fi</span></span>
</code></pre>
<p><strong>2. Build docker image locally instead of using github runner</strong></p>
<p>At that time, the standard practice to build multi-arch image is to use <a target="_blank" href="https://docs.docker.com/build/ci/github-actions/multi-platform/">qemu action</a> to translate the instructions to the target platform.</p>
<p>However, the image took more than 40 minutes to build, making this approach impractical.</p>
<p>So, I build the image locally, push it to github container registry, then manually trigger the deploy action in github.</p>
<p>This break in the deployment pipeline is a small price to pay for a much faster feedback loop. I have not kept up to date on whether a better solution is available now.</p>
<pre><code class="lang-bash">docker buildx create --platform linux/amd64,linux/arm64 --name amd64_arm64 --node amd64_arm640 --use

docker buildx build --progress=plain \
  --platform=linux/amd64,linux/arm64 \
  --target=release \
  --cache-from=<span class="hljs-built_in">type</span>=registry,ref=ghcr.io/hanchiang/market_data_notification:buildcache \
  --cache-to=<span class="hljs-built_in">type</span>=registry,ref=ghcr.io/hanchiang/market_data_notification:buildcache,mode=max \
  --tag=ghcr.io/hanchiang/market_data_notification:<span class="hljs-string">"<span class="hljs-variable">$GITHUB_COMMIT_SHA</span>"</span> \
  --push .
</code></pre>
<ol start="3">
<li><strong>Resource management for API server and chrome</strong></li>
</ol>
<p>I have also set resource limits for the API server and Chrome to prevent similar out-of-memory issues in the future.</p>
<pre><code class="lang-bash">docker run --name <span class="hljs-variable">$APP_NAME</span> -p 8080:8080 --network host --memory=<span class="hljs-string">"512m"</span> --cpus=<span class="hljs-string">"0.5"</span>
<span class="hljs-comment"># peak memory usage is around 600m</span>
docker run --name chrome -p 4444:4444 -p 5900:5900 -p 7900:7900 --network host --memory=<span class="hljs-string">"1g"</span> --cpus=<span class="hljs-string">"1"</span> -d seleniarm/standalone-chromium:114.0-20230615
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>To save some costs, I used an ARM64 processor in the production environment. This caused issues with package compatibility and longer image build times. However, the trade-off for this workaround is acceptable.</p>
<h2 id="heading-reference">Reference</h2>
<p>Market data notification post: <a target="_blank" href="https://yaphc.com/stocks-notification-tradingview-webhook-to-telegram">https://yaphc.com/stocks-notification-tradingview-webhook-to-telegram</a></p>
<p>market data notification github: <a target="_blank" href="https://github.com/hanchiang/market-data-notification">https://github.com/hanchiang/market-data-notification</a></p>
]]></content:encoded></item><item><title><![CDATA[Reverse engineering CryptoPanic REST API]]></title><description><![CDATA[Dig into JS bundle to find useful stuff]]></description><link>https://yaphc.com/reverse-engineering-cryptopanic-rest-api</link><guid isPermaLink="true">https://yaphc.com/reverse-engineering-cryptopanic-rest-api</guid><category><![CDATA[reverse engineering]]></category><category><![CDATA[cryptopanic]]></category><category><![CDATA[webdev]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 28 May 2023 13:03:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685276176582/fec37267-b5e1-46b2-8cbe-7f523767e7cd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://cryptopanic.com/">CryptoPanic</a> is a news aggregator website for trending news based on social sentiment. It's a good website for keeping up to date on the latest news, as well as using it as a trading signal.</p>
<p>Its compact layout reminds me of hacker news. I was looking through the network requests and got intrigued after finding out that the main data is not in plaintext:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684933900016/21180fe6-5d97-48ae-abbf-a18237c27228.png" alt="Posts request encrypted data" class="image--center mx-auto" /></p>
<p>The server sends some sort of encoded data, and the client decodes it. After digging around the js bundle, I manage to recover the plaintext data that is displayed on the website.</p>
<p><em>Note: This post is for educational purpose only.</em></p>
<h2 id="heading-the-reverse-engineering-process">The reverse engineering process</h2>
<h3 id="heading-1-open-the-js-bundle">1. Open the js bundle</h3>
<p>The first thing is to find out which part of the javascript code is responsible for decoding this response. Begin by searching for and opening the js bundle <code>cryptopanic.min.xxxxx.js</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684934522582/8edfd255-6ccc-4827-a3e8-2c755efdf099.png" alt="Chrome consoel js bundle" class="image--center mx-auto" /></p>
<h3 id="heading-2-locate-the-part-of-the-code-that-decodes-the-data">2. Locate the part of the code that decodes the data</h3>
<p>Searching for "decrypt" immediately zooms in on this function called <code>dc</code> that does the core work of decoding the data.</p>
<p><code>dk()</code> returns the encryption key, together with parameter <code>t</code> which is used as the Initialization Vector(IV), are passed through the AES algorithm with zero padding.</p>
<p><code>wordArrayToByteArray</code> converts the decrypted response into a byte array, and <code>pako.default.inflate</code> decompresses the data, and converts them into javascript's utf-16.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684934721630/84f85625-e91b-4c3a-832b-69c8c26a8f5e.png" alt="Decrypt and inflate" class="image--center mx-auto" /></p>
<p>After this step, the result is a JSON string of the API response. The JSON version looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685276053358/a39775b8-ba8a-41c6-a7e4-5cab0f6c7cd5.png" alt="Posts raw data" class="image--center mx-auto" /></p>
<h3 id="heading-3-transform-the-raw-response-into-a-usable-array-of-objects">3. Transform the raw response into a usable array of objects</h3>
<p>The last step is to transform the raw JSON into an array of objects so that it is easy to work with.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685275897099/2e8180ed-7701-4f68-8782-03f1b0ccd3fe.png" alt="Posts normalized data" class="image--center mx-auto" /></p>
<p>Revisiting the arguments passed to <code>dc</code> earlier, the first argument <code>t</code>(IV) is the first 16 characters of the module and some string or the CSRF token.</p>
<p>For posts API, <code>t</code> is <code>news</code> and <code>n</code> is empty.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685276708104/c94a9a2e-9b89-4dc0-b619-6e7da41331ce.png" alt="Decoding posts caller" class="image--center mx-auto" /></p>
<p>For dashboard API, <code>t</code> is also <code>news</code> while <code>n</code> is <code>rnlistrnlistrnlistrnlist</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685276913945/ebedbcc5-304a-4737-8005-530b55508413.png" alt="Decoding dashboard caller" class="image--center mx-auto" /></p>
<h3 id="heading-4-the-final-output">4. The final output</h3>
<p>This is the final output of the posts and dashboard response after decrypting, decompressing and normalizing.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685277081971/a75e011f-9512-4391-b940-ea341b13242b.png" alt="Posts normalized" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685277094868/a54111f0-113a-4f0e-bbf7-14f87b21e85f.png" alt="Dashboard normalized" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685277172266/68b886e0-959c-4b9b-9743-350803a4847c.png" alt="Cryptopanic home page highlighted" class="image--center mx-auto" /></p>
<h2 id="heading-try-it-out-yourself">Try it out yourself</h2>
<p>Here is a <a target="_blank" href="https://gist.github.com/hanchiang/ae411d08cb238ccefa0aef4b2c2899e0">gist</a> that you can use to try decoding the response yourself.</p>
<p><strong>How to use</strong></p>
<ol>
<li><p>Create an <code>.env</code> file with <code>CRYPTOPANIC_ENCRYPTION_KEY</code> and <code>CRYPTOPANIC_CSRF_TOKEN</code>.</p>
</li>
<li><p>Install the dependencies: <code>npm install dotenv pako crypto-js</code></p>
</li>
<li><p>Run <code>node decrypt.js [post|dashboard]</code></p>
</li>
</ol>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="ae411d08cb238ccefa0aef4b2c2899e0"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/hanchiang/ae411d08cb238ccefa0aef4b2c2899e0" class="embed-card">https://gist.github.com/hanchiang/ae411d08cb238ccefa0aef4b2c2899e0</a></div>]]></content:encoded></item><item><title><![CDATA[Stocks notification: TradingView webhook to telegram]]></title><description><![CDATA[Tradingview script alert + webhook -> API server -> Telegram]]></description><link>https://yaphc.com/stocks-notification-tradingview-webhook-to-telegram</link><guid isPermaLink="true">https://yaphc.com/stocks-notification-tradingview-webhook-to-telegram</guid><category><![CDATA[telegram bot]]></category><category><![CDATA[Python]]></category><category><![CDATA[side project]]></category><category><![CDATA[tradingview]]></category><category><![CDATA[Redis]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Fri, 07 Apr 2023 12:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680860732766/aea33ad6-248c-47d4-9d65-45b1cdc403f6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>At the start of the year, I worked on a telegram bot that sends market data of certain stocks for the previous day's close to a telegram channel.</p>
<p><strong>Features</strong></p>
<ul>
<li><p>Basic info such as closing price, EMA20, difference between closing price and EMA20</p>
</li>
<li><p>Overextension from EMA20 based on the median delta when stock reverse in the next few days</p>
</li>
</ul>
<p><strong>Example</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680859314366/2dc91eb9-d554-4d6f-9288-ba45382abe12.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-overview-of-the-workflow">Overview of the workflow</h2>
<ol>
<li><p>Create an indicator script in TradingView</p>
</li>
<li><p>Add indicator to chart</p>
</li>
<li><p>Set an alert using the indicator as condition, and configure webhook.</p>
</li>
<li><p>Once an alert is fired, the server saves the data in redis, and sends a notification to telegram before the market opens.</p>
</li>
</ol>
<p><strong>What's not covered</strong></p>
<p>Infrastructure(set up server, HTTPS, etc), CICD, setting up an API server</p>
<p>Other data sources: VIX central</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680443428026/87e0668b-64ad-4a63-aab1-6a5668f79bb2.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-create-a-script-in-tradingview">Create a script in TradingView</h2>
<h3 id="heading-pinescript-introduction">PineScript introduction</h3>
<p>TradingView has its own programming language called <a target="_blank" href="https://www.tradingview.com/pine-script-docs/en/v5/Introduction.html">PineScript</a>, which allows us to create indicators and trading strategies.</p>
<p>Here are some recommended readings on PineScript:</p>
<p><a target="_blank" href="https://www.tradingview.com/pine-script-docs/en/v5/language/Execution_model.html">Execution model</a> explains how the script is executed on the chart, particularly the difference between historical and real-time bars.</p>
<p><a target="_blank" href="https://www.tradingview.com/pine-script-docs/en/v5/language/Type_system.html">Types</a> and <a target="_blank" href="https://www.tradingview.com/pine-script-docs/en/v5/language/Variable_declarations.html">variable declaration</a>.</p>
<p><a target="_blank" href="https://www.tradingview.com/pine-script-docs/en/v5/concepts/Alerts.html">Alerts</a> to send data to a self-defined destination.</p>
<h3 id="heading-create-the-script">Create the script</h3>
<p><a target="_blank" href="https://gist.github.com/hanchiang/23a6ddf08d41c9aad337b13f6742990d">The script</a> that I have created retrieves the closing price and the 1D Exponential Moving Average(EMA) 20 for some tickers.</p>
<p>It uses built-in functions <a target="_blank" href="https://www.tradingview.com/pine-script-reference/v5/#fun_ta%7Bdot%7Dema">ta.ema</a> to get the EMA and <a target="_blank" href="https://www.tradingview.com/pine-script-reference/v5/#fun_request%7Bdot%7Dsecurity">request.security</a> to get data for a particular ticker and timeframe, and <code>alert.freq_once_per_bar_close</code> to send the alert when the market closes.</p>
<p><strong>Ticker name</strong></p>
<p>The ticker argument for <code>request.security</code> needs to be in the format <code>&lt;exchange&gt;&lt;ticker&gt;</code>, which can be gotten from the address bar after searching for the ticker in <a target="_blank" href="http://tradingview.com">tradingview.com</a>.</p>
<p>For SPY, it is <a target="_blank" href="https://www.tradingview.com/symbols/AMEX-SPY/">https://www.tradingview.com/symbols/AMEX-SPY/</a></p>
<p><strong>Secret</strong></p>
<p>There is a self-defined secret <code>&lt;your secret here&gt;</code>, which is used to authenticate the request in the server.</p>
<pre><code class="lang-plaintext">//@version=5
indicator("Market data notification")

ema20 = ta.ema(close, 20)

array_start = '['
array_end = ']'
json_start = '{'
json_end = '}'

build_json_array(res, symbol, timeframe, closee, ema20) =&gt;
    res + json_start + '"symbol": ' + symbol + ', "timeframe": ' + timeframe + ', "close": ' + closee + ', "ema20": ' + ema20 + json_end + ','


string[] json_key_values = array.new_string(0)

array.push(json_key_values, '"secret": "&lt;your secret here&gt;"')

data_payload = '"data": ' + array_start
data_payload := build_json_array(data_payload, '"SPY"', '"1d"', str.tostring(request.security("AMEX:SPY", "1D", close)), str.tostring(request.security("AMEX:SPY", "1D", ema20)))
data_payload := build_json_array(data_payload, '"QQQ"', '"1d"', str.tostring(request.security("NASDAQ:QQQ", "1D", close)), str.tostring(request.security("NASDAQ:QQQ", "1D", ema20)))
data_payload := build_json_array(data_payload, '"DJIA"', '"1d"', str.tostring(request.security("AMEX:DJIA", "1D", close)), str.tostring(request.security("AMEX:DJIA", "1D", ema20)))
data_payload := build_json_array(data_payload, '"IWM"', '"1d"', str.tostring(request.security("AMEX:IWM", "1D", close)), str.tostring(request.security("AMEX:IWM", "1D", ema20)))
data_payload := build_json_array(data_payload, '"AAPL"', '"1d"', str.tostring(request.security("NASDAQ:AAPL", "1D", close)), str.tostring(request.security("NASDAQ:AAPL", "1D", ema20)))
data_payload := build_json_array(data_payload, '"AMD"', '"1d"', str.tostring(request.security("NASDAQ:AMD", "1D", close)), str.tostring(request.security("NASDAQ:AMD", "1D", ema20)))
data_payload := build_json_array(data_payload, '"AMZN"', '"1d"', str.tostring(request.security("NASDAQ:AMZN", "1D", close)), str.tostring(request.security("NASDAQ:AMZN", "1D", ema20)))
data_payload := build_json_array(data_payload, '"BABA"', '"1d"', str.tostring(request.security("NYSE:BABA", "1D", close)), str.tostring(request.security("NYSE:BABA", "1D", ema20)))
data_payload := build_json_array(data_payload, '"COIN"', '"1d"', str.tostring(request.security("NASDAQ:COIN", "1D", close)), str.tostring(request.security("NASDAQ:COIN", "1D", ema20)))
data_payload := build_json_array(data_payload, '"GOOGL"', '"1d"', str.tostring(request.security("NASDAQ:GOOGL", "1D", close)), str.tostring(request.security("NASDAQ:GOOGL", "1D", ema20)))
data_payload := build_json_array(data_payload, '"META"', '"1d"', str.tostring(request.security("NASDAQ:META", "1D", close)), str.tostring(request.security("NASDAQ:META", "1D", ema20)))
data_payload := build_json_array(data_payload, '"MSFT"', '"1d"', str.tostring(request.security("NASDAQ:MSFT", "1D", close)), str.tostring(request.security("NASDAQ:MSFT", "1D", ema20)))
data_payload := build_json_array(data_payload, '"NFLX"', '"1d"', str.tostring(request.security("NASDAQ:NFLX", "1D", close)), str.tostring(request.security("NASDAQ:NFLX", "1D", ema20)))
data_payload := build_json_array(data_payload, '"NVDA"', '"1d"', str.tostring(request.security("NASDAQ:NVDA", "1D", close)), str.tostring(request.security("NASDAQ:NVDA", "1D", ema20)))
data_payload := build_json_array(data_payload, '"TSLA"', '"1d"', str.tostring(request.security("NASDAQ:TSLA", "1D", close)), str.tostring(request.security("NASDAQ:TSLA", "1D", ema20)))
data_payload := build_json_array(data_payload, '"VIX"', '"1d"', str.tostring(request.security("TVC:VIX", "1D", close)), str.tostring(request.security("TVC:VIX", "1D", ema20)))

// remove trailing comma from array
data_payload := str.substring(data_payload, 0, str.length(data_payload) - 1)
data_payload := data_payload + array_end

array.push(json_key_values, data_payload)

array.push(json_key_values, '"test_mode": "false"')

result_json = json_start + array.join(json_key_values, ',') + json_end

alert(result_json, alert.freq_once_per_bar_close)
</code></pre>
<p><strong>Add the script in tradingview</strong></p>
<p>Open the <strong>Pine Editor</strong> tab, add the script, and add it to the chart.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680447035453/4f75d953-a214-439d-9cba-c0b70a4c3296.png" alt class="image--center mx-auto" /></p>
<p><strong>Set the alert and webhook</strong></p>
<p>Set the alert using the indicator in the previous step as the condition, and configure webhook to send it to your server.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680447164094/db0dfb2f-3bb5-48b8-8a57-57c46a39e894.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680447170876/aa3393e8-cc37-47a6-9a57-56b49e3b44a2.png" alt class="image--center mx-auto" /></p>
<p>Note: Make sure the timeframe of the chart is set to daily(1D), so that the script will get triggered only once a day, when the market closes.</p>
<h2 id="heading-data-storage-redis">Data storage: Redis</h2>
<p>Redis is chosen because it fits my need for a key-value storage, and has the option to <a target="_blank" href="https://redis.io/docs/management/persistence/">persist data</a>.</p>
<h4 id="heading-data-persistence">Data persistence</h4>
<p>Redis offers 2 options: Redis Database(RDB) and Append Only File(AOF).</p>
<p>RDB is a <a target="_blank" href="https://github.com/redis/redis/blob/7.0/redis.conf#L414-L433">snapshot</a> of the data at specific intervals, while AOF is an <a target="_blank" href="https://github.com/redis/redis/blob/7.0/redis.conf#L1361-L1377">append-only log</a> of the write operations received by the server.</p>
<p>The tradeoffs of RDB and AOF complement each other, so it makes sense to use <a target="_blank" href="https://github.com/hanchiang/market-data-notification-infra/blob/master/images/scripts/install-redis.sh#L22-L25">both</a>.</p>
<p>For RDB, a snapshot will be created after 300 seconds and there is at least 1 change.</p>
<p>For AOF, write operations will be flushed to disk every second using the default fsync policy <code>appendfsync everysec</code>.</p>
<h4 id="heading-data-structure">Data structure</h4>
<p><a target="_blank" href="https://redis.io/docs/data-types/sorted-sets/">Sorted set</a> is chosen to store the data because the elements are sorted by score, which is the timestamp, and supports finding elements by score quickly.</p>
<h2 id="heading-receive-data-from-tradingview-and-post-to-telegram">Receive data from tradingview and post to telegram</h2>
<p>We need a regular API server that can receive POST request from tradingview, and send it to telegram. I wrote it in Python, using the <a target="_blank" href="https://fastapi.tiangolo.com/">FastAPI</a> framework, because it is just fast to develop with.</p>
<h3 id="heading-webhook-authenticity-check">Webhook authenticity check</h3>
<p>Since the webhook is a HTTP POST request that anyone can call, we need to ensure that it actually originates from tradingview, not someone else.</p>
<p>The first safeguard is to check the self-defined <strong>secret</strong> in the PineScript.</p>
<p>The second is to check if the request comes from one of <a target="_blank" href="https://www.tradingview.com/support/solutions/43000529348-about-webhooks/">tradingview's machines</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680448851118/3b274f6e-e8aa-45a6-b1bc-51cdf4895493.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-telegram-bot">Create telegram bot</h3>
<h4 id="heading-set-up-bot-and-channel">Set up bot and channel</h4>
<p>Follow <a target="_blank" href="https://manual.activechat.ai/fundamentals/messaging-channels/telegram">this guide</a> to create a telegram bot, and note down the token, which is used to interact with the <a target="_blank" href="https://core.telegram.org/bots/api">telegram bot API</a>.</p>
<p>Add the bot as an <strong>administrator</strong> to the channel so that it can send messages.</p>
<p><strong>Send a message to the channel</strong></p>
<p>The <strong>channel id</strong> of the channel is needed for the bot to send the message.</p>
<p>There are two ways of getting the channel id:</p>
<p>First, go to the channel on telegram web and look at the URL, which is something like <code>https://web.telegram.org/k/#-YYYYYYYYY</code>. The channel id will be <code>-100YYYYYYYYYY</code>.</p>
<p>The second method is to use <a target="_blank" href="https://t.me/username_to_id_bot">a bot</a> to tell you the channel id.</p>
<h4 id="heading-use-a-library-to-send-the-message">Use a library to send the message</h4>
<p>There are many <a target="_blank" href="https://core.telegram.org/bots/samples">client libraries</a> for different languages. I chose <a target="_blank" href="https://python-telegram-bot.org/">python-telegram-bot</a>.</p>
<h3 id="heading-cron-job">Cron job</h3>
<p>Finally, the last piece of the puzzle is to schedule the message 30 minutes before the market opens(9.30AM local time) using a cron job.</p>
<p>This is the <a target="_blank" href="https://github.com/hanchiang/market-data-notification/blob/master/src/job/stocks.py">script</a> for sending the message.</p>
<h4 id="heading-timezone">Timezone</h4>
<p>One thing to note is that the timezone changes due to daylight savings time(DST). Without DST, the timezone is Pacific Standard Time(PST), which is <strong>UTC-5</strong>. With DST, it is Pacific Daylight Time(PDT) which is <strong>UTC-4</strong>.</p>
<p>On the application side, we just need to check against the local time:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">should_run</span>() -&gt; bool:</span>
    <span class="hljs-keyword">if</span> config.get_is_testing_telegram():
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

    now = get_current_datetime()
    local = get_current_datetime()
    local = local.replace(hour=config.get_stocks_job_start_local_hour(), minute=config.get_stocks_job_start_local_minute())
    delta = now - local

    should_run = abs(delta.total_seconds()) &lt;= config.get_job_delay_tolerance_second()
    print(
        <span class="hljs-string">f'local time: <span class="hljs-subst">{local}</span>, current time: <span class="hljs-subst">{now}</span>, local hour to run: <span class="hljs-subst">{config.get_stocks_job_start_local_hour()}</span>, local minute to run: <span class="hljs-subst">{config.get_stocks_job_start_local_minute()}</span>, current hour <span class="hljs-subst">{now.hour}</span>, current minute: <span class="hljs-subst">{now.minute}</span>, delta second: <span class="hljs-subst">{delta.total_seconds()}</span>, should run: <span class="hljs-subst">{should_run}</span>'</span>)
    <span class="hljs-keyword">return</span> should_run
</code></pre>
<p>On the cron side, the script needs to run on the hour with and without DST.</p>
<p>This is the cron used to run the script at 9AM every day from monday to saturday:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># In UTC</span>
0 13,14 * * 1-6
</code></pre>
<h2 id="heading-local-development">Local development</h2>
<p>Since a webhook requires a public HTTPS endpoint, we need a reverse proxy to tunnel traffic from the public to our local server.</p>
<p><a target="_blank" href="https://ngrok.com/">Ngrok</a> is simple and easy to use.</p>
<h2 id="heading-summary">Summary</h2>
<p>This is an overview of how to use push data from Tradingview to our own server and send it to telegram.</p>
<p>Tradingview supports more complex workflows such as executing trades based on certain strategies.</p>
<h2 id="heading-reference">Reference</h2>
<p><strong>Telegram</strong></p>
<p>My channel: <a target="_blank" href="https://t.me/+6RjlDOi8OyxkOGU1">https://t.me/+6RjlDOi8OyxkOGU1</a></p>
<p>Telegram bot API: <a target="_blank" href="https://core.telegram.org/bots/api">https://core.telegram.org/bots/api</a></p>
<p>Python telegram bot: <a target="_blank" href="https://docs.python-telegram-bot.org/en/stable/">https://docs.python-telegram-bot.org/en/stable/</a></p>
<p><strong>Code</strong></p>
<p>Github link for backend: <a target="_blank" href="https://github.com/hanchiang/market-data-notification">https://github.com/hanchiang/market-data-notification</a></p>
<p>Github link for infra setup and app automation: <a target="_blank" href="https://github.com/hanchiang/market-data-notification-infra">https://github.com/hanchiang/market-data-notification-infra</a></p>
<p>API server: <a target="_blank" href="https://github.com/hanchiang/market-data-notification/blob/master/src/server.py">https://github.com/hanchiang/market-data-notification/blob/master/src/server.py</a></p>
<p>Script for sending message: <a target="_blank" href="https://github.com/hanchiang/market-data-notification/blob/master/src/job/stocks.py">https://github.com/hanchiang/market-data-notification/blob/master/src/job/stocks.py</a></p>
<p><strong>Redis</strong></p>
<p>Persistence: <a target="_blank" href="https://redis.io/docs/management/persistence/">https://redis.io/docs/management/persistence/</a></p>
<p>My persistence config: <a target="_blank" href="https://github.com/hanchiang/market-data-notification-infra/blob/master/images/scripts/install-redis.sh#L22-L25">https://github.com/hanchiang/market-data-notification-infra/blob/master/images/scripts/install-redis.sh#L22-L25</a></p>
<p><strong>TradingView PineScript</strong></p>
<p>PineScript doc: <a target="_blank" href="https://www.tradingview.com/pine-script-docs/en/v5/index.html">https://www.tradingview.com/pine-script-docs/en/v5/index.html</a></p>
<p>PineScript reference: <a target="_blank" href="https://www.tradingview.com/pine-script-reference/v5/">https://www.tradingview.com/pine-script-reference/v5/</a></p>
<p>My PineScript: <a target="_blank" href="https://gist.github.com/hanchiang/23a6ddf08d41c9aad337b13f6742990d">https://gist.github.com/hanchiang/23a6ddf08d41c9aad337b13f6742990d</a></p>
]]></content:encoded></item><item><title><![CDATA[Caching docker layers in github actions and retriggering workflow]]></title><description><![CDATA[From an almost fully automated pipeline to a fully automated pipeline]]></description><link>https://yaphc.com/caching-docker-layers-in-github-actions-and-retriggering-workflow</link><guid isPermaLink="true">https://yaphc.com/caching-docker-layers-in-github-actions-and-retriggering-workflow</guid><category><![CDATA[GitHub Actions]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Tue, 01 Nov 2022 12:21:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/dkN5z8IdkFk/upload/v1667305074922/Tyobrsa9d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Following my previous post on <a target="_blank" href="https://www.yaphc.com/automating-infrastructure-provisioning-configuration-and-application-deployment">automating infrastructure provisioning, configuration and application deployment</a>, there are 2 areas that I wanted to improve.</p>
<h2 id="heading-cache-docker-layers-in-deploy-workflow">Cache docker layers in deploy workflow</h2>
<p>First, docker layers in the build step of the <a target="_blank" href="https://github.com/hanchiang/url-shortener-backend/blob/master/.github/workflows/deploy.yml">deploy workflow</a> should be cached.</p>
<p>The <a target="_blank" href="https://github.com/docker/build-push-action">build-push-action</a> github action can build, push, and cache the docker image.</p>
<div class="hn-embed-widget" id="urlshortener-github-actions-cache-docker-layers"></div><p> </p>
<p>With this simple modification, the deployment workflow is shortened by 3 minutes.</p>
<p>This may not be significant, but it is useful for me as I have a script to start and stop the application, which is triggered on schedule via github actions in the <a target="_blank" href="https://github.com/hanchiang/url-shortener-infra/tree/master/.github/workflows">infra repository</a>.</p>
<p>I can also run the script manually when I am debugging an issue, whether it is on infrastructure configuration or application deployment.</p>
<h2 id="heading-dispatch-workflow-dont-re-run-workflow-job">Dispatch workflow, don't re-run workflow job</h2>
<p>Next, <a target="_blank" href="https://docs.github.com/en/rest/actions/workflows#create-a-workflow-dispatch-event">dispatch a workflow</a> instead of <a target="_blank" href="https://docs.github.com/en/actions/managing-workflow-runs/re-running-workflows-and-jobs">re-running a workflow job</a>.</p>
<p>This is because the maximum log retention is 30 days, so re-running a job that is older than 30 days will fail.</p>
<blockquote>
<p>You can re-run a workflow run, all failed jobs in a workflow run, or specific jobs in a workflow run up to 30 days after its initial run.</p>
</blockquote>
<pre><code class="lang-plaintext">deploy_workflow=$(curl  -H "Accept: application/vnd.github+json" -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/repos/hanchiang/url-shortener-backend/actions/workflows |  jq '.workflows[] | select(.state == "active" and select(.name | ascii_downcase | contains("build and deploy")))')

workflow_id=$(echo $deploy_workflow | jq -r .id)
curl -X POST  -H "Accept: application/vnd.github+json" -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/repos/hanchiang/url-shortener-backend/actions/workflows/$workflow_id/dispatches \
 -d '{"ref":"master"}'
</code></pre>
<p>Before this modification, I have to manually dispatch a workflow in the github actions UI every 30 days. With this, the entire infrastructure configuration and application deployment pipeline is now fully automated 😄</p>
]]></content:encoded></item><item><title><![CDATA[Automating infrastructure provisioning, configuration, and application deployment]]></title><description><![CDATA[provision(packer, terraform) -> configuration(ansible) -> deployment(github actions)]]></description><link>https://yaphc.com/automating-infrastructure-provisioning-configuration-and-application-deployment</link><guid isPermaLink="true">https://yaphc.com/automating-infrastructure-provisioning-configuration-and-application-deployment</guid><category><![CDATA[Infrastructure as code]]></category><category><![CDATA[Terraform]]></category><category><![CDATA[github-actions]]></category><category><![CDATA[Docker]]></category><category><![CDATA[packer]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sat, 30 Jul 2022 09:17:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659172176048/S8GZWEFwU.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a software engineer, I read and write application code every day. Occasionally, I get to work a little on CI/CD pipeline - Fix build issues, deploy a new application, etc. However, I have little understanding of how the entire process is orchestrated and automated.</p>
<p>So, I began with the goal of learning how to automate the entire stack: from infrastructure <strong>provisioning</strong>, <strong>configuration</strong>, application <strong>deployment</strong>, and starting and stopping the stack itself.</p>
<p>After spending some time crawling through Reddit and Stack Overflow, I gained a basic understanding of the whole process and the tools that are commonly used.</p>
<h2 id="heading-overview">Overview</h2>
<p>The target application is a <a target="_blank" href="https://urlshortener.yaphc.com/">URL shortener</a> that makes a long URL into a shorter one, like <a target="_blank" href="https://tinyurl.com">TinyURL</a>.</p>
<p>Backend repository: https://github.com/hanchiang/url-shortener-backend</p>
<p>Infra repository: https://github.com/hanchiang/url-shortener-infra</p>
<p>Technologies used:</p>
<ul>
<li><p>Provisioning: packer, terraform</p>
</li>
<li><p>Configuration: ansible</p>
</li>
<li><p>Deployment: docker, github actions</p>
</li>
<li><p>Cloud computing: AWS EC2</p>
</li>
</ul>
<p><strong>Provisioning, configuration, deployment</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659163892638/_FDRD2nby.png" alt="deployment-pipeline.drawio.png" /></p>
<h2 id="heading-what-is-provisioning-configuration-and-deployment">What is provisioning, configuration, and deployment?</h2>
<p>It can be confusing to understand what provisioning, configuration, and deployment mean exactly.</p>
<p>My understanding is summarised in a timeline: provisioning -&gt; configuration -&gt; deployment</p>
<p><strong>Provisioning</strong></p>
<p>Provisioning is the process of setting up servers to be ready for use. In the context of cloud computing, this server is likely a <strong>virtual machine</strong>, on which a machine image is installed. Here, the operating system, along with other required software is installed.</p>
<p>In AWS terms, this means creating a VPC, subnet, route table, and EC2.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659153623858/1VscWWRlW.png" alt="iaas-paas-saas-diagram.png" /></p>
<p>Source: <a target="_blank" href="https://www.redhat.com/en/topics/cloud-computing/iaas-vs-paas-vs-saas">redhat</a></p>
<p>The diagram above is useful to remember which layers we have to take care of under different cloud computing models.</p>
<p><strong>Configuration</strong></p>
<p>Configuration can be considered as an extension to the process of provisioning the server. Once the server is created, and loaded with the required software, it needs to be configured so that it is usable.</p>
<p>e.g. Configure PostgreSQL data directory, logging and authentication settings</p>
<p><strong>Deployment</strong></p>
<p>With the infrastructure ready to serve live traffic, an application can finally be deployed from an artifact repository to the server.</p>
<p>This could be as simple as SSH into the server, pulling a docker image, and running a container, or deploying to a kubernetes cluster with helm.</p>
<p><strong>Visualising the whole pipeline</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659164575324/TjP0LHbV_.png" alt="infrastructure and code.png" /></p>
<p>Source: <a target="_blank" href="https://www.golibrary.co/infrastructure-as-code-orchestration-provisioning-configuration-management-ansible-terraform">golibrary</a></p>
<h2 id="heading-deployment">Deployment</h2>
<p>I chose deployment as the first step because this is the easiest part of the pipeline. After building features and committing code, the next step is to deploy the new application.</p>
<p><strong>Application setup</strong></p>
<p>The URL shortener application is built on docker. Docker compose is used for the convenience of local setup. It consists of 3 containers: nodejs server, postgres, redis</p>
<div class="hn-embed-widget" id="urlshortener-docker-compose"></div><p> </p>
<p><strong>Deploying the application</strong></p>
<p>Application deployment is done with <a target="_blank" href="https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions">github actions</a>.</p>
<div class="hn-embed-widget" id="urlshortener-github-actions-deploy"></div><p> </p>
<p>The docker image is built and pushed to Github container registry. Then, it connects to the EC2 instance via SSH, pulls and runs the new image.</p>
<h2 id="heading-provisioning">Provisioning</h2>
<p>With the deployment part of the process handled, let's move on to provisioning the server.</p>
<p>There are 2 parts to provisioning:</p>
<ul>
<li><p>Build a system image with all the necessary software</p>
</li>
<li><p>Build the infrastructure and servers</p>
</li>
</ul>
<h3 id="heading-building-image-with-packer">Building image with packer</h3>
<p><a target="_blank" href="https://www.packer.io/">Packer</a> is used to create a golden <a target="_blank" href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html">AMI</a> with software and configurations, which is installed on the EC2 instance.</p>
<p>I used packer to create a user, install PostgreSQL, Redis, Nginx, Docker.</p>
<p>Using packer here takes advantage of <a target="_blank" href="https://www.bridge-global.com/blog/mutable-vs-immutable-infrastructure">immutable infrastructure</a>, in which a standardised fleet of servers is built, achieving consistency and maintainability.</p>
<div class="hn-embed-widget" id="urlshortener-packer"></div><p> </p>
<h3 id="heading-building-infrastructure-with-terraform">Building infrastructure with terraform</h3>
<p>After that, the infrastructure is <strong>orchestrated</strong> with <a target="_blank" href="https://www.terraform.io/">Terraform</a>. It takes care of creating a VPC, subnet, EC2, route table, security groups.</p>
<p>Terraform is a tool that allows us to build the entire infrastructure in the <strong>correct order</strong>, and keeps track of the <strong>desired state</strong>, in a declarative style.</p>
<p>It can also detect state drift by synchronising its state to match the real-world state.</p>
<p>Again, the benefits of consistency and maintainability are present.</p>
<div class="hn-embed-widget" id="urlshortener-terraform"></div><p> </p>
<h2 id="heading-configurations">Configurations</h2>
<p>Lastly, configurations is the missing middle piece in the entire pipeline.</p>
<p>After the system image is built with packer, and AWS infrastructure created with terraform, there are a few configuration tasks that need to be done in order for the server to be ready to serve live traffic.</p>
<p>This is done with <a target="_blank" href="https://www.ansible.com/use-cases/configuration-management">Ansible</a>, which is a simple yet powerful tool that allows us to configure servers in yaml.</p>
<p><em>I am using ansible to run shell scripts imperatively instead of managing configurations declaratively using the pre-defined modules, because I found it the easiest way to learn</em></p>
<h3 id="heading-set-up-file-system-for-postgres">Set up file system for postgres</h3>
<p>Set up file system on a <a target="_blank" href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html">separate EBS volume</a> to store postgres data, and other relevant data.</p>
<p>The reason for using separate storage from the root volume is so that all my application data is preserved each time a new server is provisioned.</p>
<div class="hn-embed-widget" id="urlshortener-setup-file-system-ansible"></div><p> </p>
<h3 id="heading-configure-postgres">Configure postgres</h3>
<p>Configure postgres data directory and copy data over.</p>
<div class="hn-embed-widget" id="urlshortener-copy-postgres-data-ansible"></div><p> </p>
<h3 id="heading-configure-nginx">Configure Nginx</h3>
<p>Configure SSL on nginx, redirect HTTP to HTTPS, and proxy all requests to the port that the URL shortener container is listening on.</p>
<div class="hn-embed-widget" id="urlshortener-nginx-ansible"></div><p> </p>
<h2 id="heading-schedule-start-and-stop">Schedule start and stop</h2>
<p>As an additional step, I wanted to schedule the start and stop of the EC2 and application via <a target="_blank" href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule">scheduled workflow in github actions</a>.</p>
<p>This consist of the tasks defined in the configuration step, as well as interaction with <a target="_blank" href="https://aws.amazon.com/cli/">AWS CLI</a> and <a target="_blank" href="https://docs.github.com/en/rest">Github API</a>.</p>
<p>The script can be found <a target="_blank" href="https://github.com/hanchiang/url-shortener-infra/blob/master/instances/scripts/start.sh">here</a></p>
<h2 id="heading-summary">Summary</h2>
<p>The end result is a complete pipeline from infrastructure provisioning to application deployment. Now that I have a basic understanding of DevOps, my next step is to explore <a target="_blank" href="https://iamondemand.com/blog/the-3-pillars-of-system-observability-logs-metrics-and-tracing">observability</a>.</p>
<p><strong>Check out the project</strong></p>
<p>Website: <a target="_blank" href="https://urlshortener.yaphc.com/">URL shortener</a></p>
<p>Backend repository: https://github.com/hanchiang/url-shortener-backend</p>
<p>Infra repository: https://github.com/hanchiang/url-shortener-infra</p>
]]></content:encoded></item><item><title><![CDATA[Hashnode: A home for my blog]]></title><description><![CDATA[wordpress -> JAMstack(hugo, gatsby, ghost) -> wordpress(again) -> hashnode]]></description><link>https://yaphc.com/hashnode-a-home-for-my-blog</link><guid isPermaLink="true">https://yaphc.com/hashnode-a-home-for-my-blog</guid><category><![CDATA[Blogging]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 05 Jun 2022 12:55:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/gWlBxOAgXgQ/upload/v1654433674086/2DjziVnNu.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A few days ago, I discovered <a target="_blank" href="https://hashnode.com">Hashnode</a>, a blogging platform and community for tech folks to share knowledge and ideas.</p>
<p>From a quick glance at the homepage, it seems like the dream platform for tech writers. All you have to do is to focus on writing content, while Hashnode takes care of everything else:</p>
<ul>
<li><p>Own your content</p>
</li>
<li><p>No ads or paywall</p>
</li>
<li><p>Reach a wide audience</p>
</li>
<li><p>Built-in analytics and various integrations</p>
</li>
<li><p>Easy authoring with markdown</p>
</li>
<li><p>SEO</p>
</li>
<li><p>Custom CSS</p>
</li>
<li><p>Backup with GitHub 😎</p>
</li>
<li><p>Article series 🤩</p>
</li>
<li><p>Built-in newsletter 🤩</p>
</li>
<li><p>Bonus: Built on Next.js, powered by Vercel 😎</p>
</li>
</ul>
<p>These alone piqued my interest, and I signed up for an account to give it a try.</p>
<h2 id="heading-history-of-my-website">History of my website</h2>
<p><strong>Wordpress</strong> I created my website sometime in 2016. I chose WordPress, self-hosted on Digital Ocean because I wanted to focus on writing only while retaining full ownership of my content.</p>
<p><strong>JAMstack</strong> Shortly after, <a target="_blank" href="https://jamstack.org/">JAMstack</a> became a popular way of managing blogs because there are no more servers involved in the stack, eliminating <strong>costs</strong>, and improving the <strong>performance</strong> and <strong>security</strong> of websites.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654415043425/lCmA7dSFs.png" alt="google trends jamstack.png" /></p>
<p>So, I experimented with Static Site Generators(SSG) like <a target="_blank" href="https://gohugo.io/">Hugo</a> which is based on Go, <a target="_blank" href="https://www.gatsbyjs.com/">Gatsby</a> which is based on React. The developer in me found it fun to have full control in deciding how the content is stored and shaping the user experience.</p>
<p>However, the excitement died off quickly as I drifted away from my initial goal and found myself spending more and more time customizing layouts, adding social sharing integrations, SEO, analytics, image compression, etc</p>
<p><strong>Ghost</strong> So, I switched to self-hosting <a target="_blank" href="https://yaphc.com/blog-ghost-platform">Ghost</a>. It offers a clean writing experience, with cards for rich media and great out-of-the-box SEO.</p>
<p>Later on, I experimented with downloading a local copy of the website and <a target="_blank" href="https://yaphc.com/ghost-blog-static-website">hosting it as a static site</a> on Netlify, in the spirit of JAMstack.</p>
<p>It was almost perfect, except I found myself having to dive into customising the theme to add basic features like social links, breaking my rule of wanting to focus on writing again.</p>
<p><strong>Back to wordpress</strong></p>
<p>So, I moved my website back to wordpress and lived with the plugin life.</p>
<p><strong>To Hashnode</strong></p>
<p>Finally, my website ended up on Hashnode. Hashnode solves all the problems that I have faced previously and really allows me to focus just on writing while allowing me to own my content.</p>
<p>I used this <a target="_blank" href="https://kumarashwinhubert.com/how-to-migrate-your-blog-from-wordpress-to-hashnode">guide</a> to migrate my website from Wordpress to Hashnode. It is simple, except for image handling - I have to manually upload them one by one. 😢</p>
<h2 id="heading-a-tour-of-hashnode">A tour of Hashnode</h2>
<h3 id="heading-home-feed">Home feed</h3>
<p>The home feed is in a three-column format, similar to <a target="_blank" href="https://dev.to/">DEV</a>. There's a navigation bar on the left, a main content block in the center, and a utility column on the right.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654418656381/G74KQzGIn.png" alt="hashnode home feed.png" /></p>
<h3 id="heading-editor">Editor</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654419583773/XPYpYZJ26.png" alt="hashnode editor.png" /></p>
<p>The editor provides a clean, distraction-free space to write your content, much like Ghost did. It supports standard content tools such as links, code snippets, and images.</p>
<p><strong>Settings flyout</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654419822450/kMT0xFJwcF.png" alt="hashnode editor flyout.png" /></p>
<p>Clicking the "<strong>...</strong>" and "<strong>Settings</strong>" at the top right will open the settings flyout on the right side. Here, you can adjust various settings to get ready for publishing. I especially like the feature that auto-generates a table of contents.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654419865418/5s88_923I.png" alt="hashnode editor flyout 2.png" /></p>
<p>Skipping ahead, you can also schedule your article, backdate it, hide comments, and hide the article from the community.</p>
<p>Hashnode does a great job of using built-in analytics to help you choose the best day to publish your post. 👍</p>
<h3 id="heading-dashboard">Dashboard</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654424850009/GNTS7Biya.png" alt="hashnode dashboard top view.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654424883367/bMPCgNmmg.png" alt="hashnode dashboard bottom view.png" /></p>
<p>On the dashboard page, there is a general navigation bar on top, a call-to-action hero section, and the main navigation bar on the left which is grouped according to their functions.</p>
<p>This page is one of my favourite parts of Hashnode. It has all the essential batteries included in a content-sharing platform.</p>
<p>For authoring, I can write drafts and articles, create a static page, create a <strong>series</strong> and add articles under it.</p>
<p>It has great built-in <strong>analytics</strong>, with an even greater advanced analytics page which is currently in beta.</p>
<p>I can embed elements from various platforms by defining them as <strong>widgets</strong>, and integrate them with services like google analytics, hotjar, <a target="_blank" href="https://webmonetization.org/">web monetisation</a>. There is even a <strong>newsletter</strong> service out of the box! 🤩</p>
<p>I can also set a <strong>custom domain</strong>, <strong>backup</strong> content to Github, export data, and more.</p>
<h3 id="heading-analytics">Analytics</h3>
<p>Now, let's look at the amazing analytics page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654426014148/lXBsLU_NC.png" alt="hashnode dashboard analytics 1.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654430472852/wrb3oXqyC.png" alt="hashnode dashboard analytics 2.png" /></p>
<p>At the top is a summary of the number of views over a period of time. As I have just started on Hashnode yesterday, there is data only for 4 June 2022. Scrolling down, you can see the number of views, comments, and reactions to your articles in reverse chronological order.</p>
<h4 id="heading-advanced-analytics">Advanced analytics</h4>
<p>This is where analytics gets even more awesome.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654430847152/mEsm3S6xw.png" alt="hashnode dashboard analytics beta 1.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654430905376/cCy3FYE4Y.png" alt="hashnode dashboard analytics beta 2.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654430918545/uKcXUc7kW.png" alt="hashnode dashboard analytics beta 3.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654430931764/1O7p7sjPN.png" alt="hashnode dashboard analytics beta 4.png" /></p>
<p>You can see the number of visitors within a date range, by page, traffic source, browser, device, and operating system. Although it is not a full-fledged analytics service like Google Analytics, the important data points are presented in a simple UI and are easy to understand.</p>
<h3 id="heading-article-view">Article view</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654435280623/3dOo7zGpX.png" alt="hashnode post view text selection sharer.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654435577511/AnLUva5RT.png" alt="hashnode post view sticky table of content.png" /></p>
<p>The reading experience is great too. The article page has two columns: a main content block that is centered, and a right sticky bar for reactions and social sharing.</p>
<p>The table of contents is displayed neatly at the top, indented according to the headings.</p>
<p>As you scroll down, the table of contents sticks to the top of the page, allowing you to easily navigate to a particular section. No more scrolling up and down. This is a win for content discovery and can save a lot of time if the article is long.</p>
<p>There is also a handy feature that lets you select text and share it on social media.</p>
<h3 id="heading-run-out-of-ideas-request-for-articles-comes-to-the-rescue">Run out of ideas? Request for articles comes to the rescue!</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654432103212/TgV1I_DOy.png" alt="hashnode request for articles.png" /></p>
<p>One of the biggest problems writers face is coming up with ideas.</p>
<p>Hashnode has a useful feature called <a target="_blank" href="https://hashnode.com/rfa">Request For Articles (RFA)</a>. It's a page where people request articles on various topics, and writers can use these requests for content ideas. Even better, after you write an article for a specific RFA, you can add the link to your article, and it will be attached to the RFA.</p>
<p>This crowdsourcing of content is a great way to generate interesting ideas and keep the community engaged.</p>
<h3 id="heading-documentation">Documentation</h3>
<p>Every developer appreciates a well-written <a target="_blank" href="https://support.hashnode.com/docs">documentation</a>. The documentation is well organised, making it easy to search for anything you are looking for. Again, a plus point for content discovery. 👍</p>
<h2 id="heading-what-could-be-better">What could be better</h2>
<h3 id="heading-editor-preview-page">Editor preview page</h3>
<p>If you scroll back up to the <a class="post-section-overview" href="#heading-editor">Editor</a> section, you can see that there is a preview tab that allows you to see what your article looks like.</p>
<p>The preview is rendered in the same content block as the article, resulting in excessive scrolling up and down to switch between writing mode and preview mode.</p>
<p>It would be great to have the preview mode as a <strong>flyout</strong> instead of being rendered in the same content block as the article so that writers won't have to scroll all the way up to switch mode, scroll down to look at the rendered content, and repeat them over and over again.</p>
<h3 id="heading-publishedupdated-content-not-displayed-when-the-back-button-is-clicked">Published/updated content not displayed when the back button is clicked</h3>
<p>I noticed that after updating an article and returning to the editor page by clicking the back button, the changes did not appear. Instead, I saw the old content. However, after refreshing the page, the changes were visible.</p>
<p>I found out about this when I updated an article, such as checking the auto-generate table of content, returning to the editor page, making some other changes, and realised that the table of content disappeared.</p>
<p>This may not a big issue but could be frustrating if a huge update was made, only to be overwritten by another small update.</p>
<h3 id="heading-newsletter-ended-up-in-junk-mail">Newsletter ended up in junk mail</h3>
<p>I tried out the newsletter service, which is really simple to use. All I have to do is to flip a toggle, and the newsletter subscription box shows up on the website.</p>
<p>However, the newsletter ended up in the junk mail for hotmail. 😢 For Gmail, it shows up in the inbox as expected.</p>
<h2 id="heading-summary">Summary</h2>
<p>After just 1 day of using Hashnode, I can say that I really enjoy using it. It takes care of everything, allowing me to focus on just the writing part.</p>
<p>Note that at this point of writing, Hashnode has been running for around 2 years, and has raised $6.7M in the <a target="_blank" href="https://www.crunchbase.com/organization/hashnode/company_financials">series A round on 18 August 2021</a>.</p>
<p>As of now, they are still in the growth phase in which the focus is on <strong>building and expanding</strong> the core product, not on monetisation.</p>
<p>After the platform has reached a certain level of maturity, the focus will shift toward <strong>profitability</strong>. Let's see if they will continue to support all the existing features or put some of them behind a paywall.</p>
<p>I hope the team continues to do well, just as they have been, and that I can use this platform for a long time.</p>
<h2 id="heading-join-me">Join me</h2>
<p>If you like what you see about Hashnode so far, you can sign up <a target="_blank" href="https://hashnode.com/@hanchiang/joinme">referral link</a>.</p>
<p>I do not earn a commission for referrals, but I will be able to qualify for the <a target="_blank" href="https://hashnode.com/ambassador">ambassador</a> role that provides perks like access to beta features, converting articles into audio, etc.</p>
]]></content:encoded></item><item><title><![CDATA[Implementing redis serialisation protocol]]></title><description><![CDATA[This is a follow-up post from Building redis with CodeCrafters. When I first started the redis challenge, I did the quick and dirty way of bypassing the…]]></description><link>https://yaphc.com/implementing-redis-serialisation-protocol</link><guid isPermaLink="true">https://yaphc.com/implementing-redis-serialisation-protocol</guid><category><![CDATA[side project]]></category><category><![CDATA[Redis]]></category><category><![CDATA[Rust]]></category><category><![CDATA[TCP]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 29 May 2022 04:13:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654315962022/AO4ObI5sD.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a follow-up post from <a target="_blank" href="https://www.yaphc.com/building-redis-with-codecrafters-challenge">Building redis with CodeCrafters</a>.</p>
<p>When I first started the redis challenge, I did the <a target="_blank" href="https://github.com/hanchiang/codecrafters-redis-rust/blob/0.0.1/src/request_response/client_input.rs">quick and dirty</a> way of bypassing the redis serialisation protocol in order to make things work.</p>
<p><strong>Redis serialisation protocol implementation</strong></p>
<p>In the <a target="_blank" href="https://github.com/hanchiang/codecrafters-redis-rust/releases/tag/0.2.0">next release</a>, I implemented the <a target="_blank" href="https://redis.io/docs/reference/protocol-spec/">redis serialisation protocol</a>, which can handle a few data types: simple string, bulk string, error, integer, array.</p>
<p>It was a great exercise that puts recursion into practice. Working with raw bytes is much more performant than converting them to string every time.</p>
<p><strong>Integrate redis serialisation protocol</strong></p>
<p>Next up is to <a target="_blank" href="https://github.com/hanchiang/codecrafters-redis-rust/releases/tag/0.3.0">integrate</a> the parser with the codebase. There was quite a bit of code because the older method of parsing input is totally different from this new implementation.</p>
<p>This shows the importance of design a clean interface before writing code. The underlying implementation may change, but a big rewrite will be avoided as long as the interface is still valid.
In this case, the interface of these two methods is completely different, resulting in a breaking change in the parser.</p>
<p>Finally, examples of usage are updated to be clearer and user friendly</p>
<p>Check it out <a target="_blank" href="https://github.com/hanchiang/codecrafters-redis-rust">here</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Building redis with CodeCrafters]]></title><description><![CDATA[A follow-up to this article can be found here CodeCrafters is an amazing community built by Paul Kuruvilla that contains project challenges for real-world…]]></description><link>https://yaphc.com/building-redis-with-codecrafters-challenge</link><guid isPermaLink="true">https://yaphc.com/building-redis-with-codecrafters-challenge</guid><category><![CDATA[side project]]></category><category><![CDATA[Redis]]></category><category><![CDATA[Rust]]></category><category><![CDATA[TCP]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sat, 19 Mar 2022 05:32:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654320760899/-kfkhgjFM.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>A follow-up to this article can be found <a target="_blank" href="https://yaphc.com/implementing-redis-serialisation-protocol">here</a></em></p>
<p><a target="_blank" href="https://codecrafters.io/">CodeCrafters</a> is an amazing community built by <a target="_blank" href="https://twitter.com/rohitpaulk">Paul Kuruvilla</a> that contains project challenges for real-world software systems that are used widely(redis, git, docker, SQLite).</p>
<p>Each project comes in the form of guided steps on what you will build and leaves enough room for you to acquire new knowledge and apply them.</p>
<p>As a follow-up to my previous post on <a target="_blank" href="https://www.yaphc.com/learning-a-system-programming-language-rust">learning Rust</a>, as well as my personal goals of working with technology at lower levels, I tried the <a target="_blank" href="https://app.codecrafters.io/courses/redis/overview">Redis challenge</a> with Rust, which is at the beginner level, and had a blast with it.</p>
<h2 id="heading-the-learning-experience">The learning experience</h2>
<p>A starter project is provided to help you get started. Each time code is pushed to the repository, the CodeCrafters server will run your code against its own test cases and the output is streamed to your console.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654320876525/pqTxSX9Tk.png" alt="git-push-streaming-logs.png" /></p>
<p>Here are the steps in the redis challenge.</p>
<p><strong>1. Set up</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654320903519/npFedN4l3.png" alt="1.-setup-redis.png" /></p>
<p><strong>2. Bind to a port</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654320945947/VHI9VJmRs.png" alt="2.-bind-to-a-port.png" /></p>
<p><strong>3. Respond to PING</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654320984345/x9eBXzy3D.png" alt="3.-respond-to-ping.png" /></p>
<p><strong>4. Respond to multiple PINGs</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321011060/CVnvNO3P6.png" alt="4.-respond-to-multiple-pings.png" /></p>
<p><strong>5. Handle concurrent clients</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321037625/HDpKd-vKD.png" alt="5.-handle-concurrent-clients.png" /></p>
<p><strong>6. Implement ECHO</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321066479/goCl6gpS-.png" alt="6.-implement-echo-command.png" /></p>
<p><strong>7. Implement SET and GET</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321086078/ZRtTopv_V.png" alt="7.-implement-get-and-set-command.png" /></p>
<p><strong>8. SET with expiry</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321174270/Q7nvP_ApU.png" alt="8.-set-with-expiry.png" /></p>
<p><strong>Challenge complete</strong></p>
<p>After completing the first challenge in CodeCrafters, you will get a cool profile page that shows your progress.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321194743/Ckbcok3Xp.png" alt="redis-challenge-complete.png" /></p>
<p>As you can see, the challenge comes in a series of tasks that are built on top of the previous ones. Links to learning resources are provided, nothing more than that.</p>
<p>However, if you are stuck on a certain task, there is a discord community in which you can ask for help. The creator himself is very active.</p>
<p>The website also has a useful FAQ bot for general debugging.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321218390/6ckoZjtfW.png" alt="FAQ-chat-bot.png" /></p>
<p>FAQ bot</p>
<h2 id="heading-thoughts">Thoughts</h2>
<p>I really enjoyed the learning experience that CodeCrafters provides as there is just enough material for me to start learning and building on my own. It is fun, and is the best way to learn a programming language - learn by doing.</p>
<p>The website is super friendly, easy to navigate, easy to get help via FAQ bot and discord.</p>
<p>Going through multiple courses is useful only up to a certain point because many of them hold your hands throughout every step, leaving little room for independent learning.</p>
<p>For people who "don't know what to build", including me, this is a good place to start, and I cannot think of something better.</p>
<p>Overall, I highly recommend anyone who wants to learn a programming language and build a project at the same time to use CodeCrafters.</p>
<p>Here is my completed project on <a target="_blank" href="https://github.com/hanchiang/codecrafters-redis-rust">github</a>. Feel free to check it out and leave suggestions for improvements.</p>
]]></content:encoded></item><item><title><![CDATA[Learning a system programming language: Rust]]></title><description><![CDATA[I have spent the past few weeks learning Rust through the official book: The rust programming language, and enjoyed the experience. It is written by Steve…]]></description><link>https://yaphc.com/learning-a-system-programming-language-rust</link><guid isPermaLink="true">https://yaphc.com/learning-a-system-programming-language-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Fri, 18 Feb 2022 05:45:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654321456742/KHmxw54h9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have spent the past few weeks learning Rust through the official book: <a target="_blank" href="https://doc.rust-lang.org/stable/book/">The rust programming language</a>, and enjoyed <a target="_blank" href="https://github.com/hanchiang/learn-rust">the experience</a>. It is written by <a target="_blank" href="https://twitter.com/steveklabnik?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Steve Klabnik</a>, one of the former contributors of Rust.</p>
<p>I started learning Rust in 2019, left it, and only came back to it recently.</p>
<h2 id="heading-why-systems-programming">Why systems programming?</h2>
<p>I have been doing high-level web development for 3 years, and I wanted to work with technology at a lower level.</p>
<h2 id="heading-why-rust">Why Rust?</h2>
<p>Besides being the <a target="_blank" href="https://insights.stackoverflow.com/survey/2021">most-loved language</a> for consecutive years, Rust is designed to match the performance of C++, while providing memory safety, which is a safeguard for programmers against making such mistakes.</p>
<p>Interestingly, it is able to do so without the use of a garbage collector, through a concept known as <a target="_blank" href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html">ownership</a>, and this is one of the unique selling points of Rust.</p>
<h2 id="heading-the-rust-programming-language-book">The Rust programming language book</h2>
<p>As mentioned, the book is well written and covers everything you need to get started with Rust - data types, control structures, error handling, tests, packaging, concurrency, mini-projects.</p>
<p>Here are some of my favourite chapters:</p>
<p><a target="_blank" href="https://doc.rust-lang.org/stable/book/ch04-00-understanding-ownership.html"><strong>4. Understanding ownership</strong></a></p>
<p>The concept of ownership is new and is Rust's unique selling point. The idea is that any heap-allocated data can only have 1 owner, so that freeing up the memory is straightforward.</p>
<p>This new way of approaching memory deallocation is new and takes time to get used to.</p>
<p><a target="_blank" href="https://doc.rust-lang.org/book/ch06-00-enums.html"><strong>6. Enums and Pattern Matching</strong></a></p>
<p>Pattern matching using the <em>match</em> keyword enforce exhaustibility, i.e. Rust makes sure we handle every possible pattern, otherwise the program won't compile.</p>
<p>Together with pre-defined enums such as <a target="_blank" href="https://doc.rust-lang.org/std/option/">Option</a>, working with complex conditionals and variables that may or may not contain a value becomes a simple task.</p>
<p><a target="_blank" href="https://doc.rust-lang.org/book/ch09-00-error-handling.html"><strong>9. Error Handling</strong></a></p>
<p>Building on enums and pattern matching, handling recoverable errors is a joy with the <a target="_blank" href="https://doc.rust-lang.org/std/result/enum.Result.html">Result</a> enum, which contains the <em>Ok</em> variant if an operation succeeds, and the <em>Err</em> variant if it fails.</p>
<p>For uncoverable errors, simply use the <a target="_blank" href="https://doc.rust-lang.org/std/macro.panic.html">panic!</a> macro.</p>
<p><a target="_blank" href="https://doc.rust-lang.org/stable/book/ch15-00-smart-pointers.html"><strong>15. Smart pointers</strong></a></p>
<p>Smart pointers are pointers that behave like references, but with additional capabilities such as <a target="_blank" href="https://doc.rust-lang.org/std/ops/trait.Deref.html">dereferencing coercion</a>, <a target="_blank" href="https://doc.rust-lang.org/std/ops/trait.Drop.html">cleaning up resources</a> after they are no longer needed.</p>
<p>Using a smart pointer such as <a target="_blank" href="https://doc.rust-lang.org/std/rc/struct.Rc.html">Rc</a> allows a value to have multiple owners, and they are tracked and deallocated accordingly.</p>
<p><a target="_blank" href="https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html"><strong>16. Fearless concurrency</strong></a></p>
<p>Concurrent programming is important to any large-scale, high-load systems.</p>
<p>The concept of channels(similar to golang) allows threads to pass messages between one another, and mutex to allow threads access to shared resources.</p>
<p><a target="_blank" href="https://doc.rust-lang.org/stable/book/ch12-00-an-io-project.html"><strong>12. An I/O project: Building a command line program</strong></a> and <a target="_blank" href="https://doc.rust-lang.org/stable/book/ch20-00-final-project-a-web-server.html">20. Final project: building a multithreaded web server</a></p>
<p>These 2 chapters walk through the process of building simple projects using the concepts learned so far and apply them in the context of proper software engineering practices such as <a target="_blank" href="https://en.wikipedia.org/wiki/SOLID">SOLID</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>.</p>
<h2 id="heading-summary">Summary</h2>
<p>I enjoyed the process of learning Rust. Thinking about how I handle data has made me a better programmer. It also made programming fun again.</p>
<p>I may not use Rust for work anytime soon, but this new way of thinking about ownership has made me more aware of what happens behind the scenes.</p>
]]></content:encoded></item><item><title><![CDATA[Project venturebites: A portal for asia tech startup events]]></title><description><![CDATA[Earlier this year(2021), I worked on Venturebites with a friend, which is a portal for tech startup events in Asia. I was actively working on it for 2…]]></description><link>https://yaphc.com/project-venturebites-a-portal-for-asia-tech-startup-events</link><guid isPermaLink="true">https://yaphc.com/project-venturebites-a-portal-for-asia-tech-startup-events</guid><category><![CDATA[side project]]></category><category><![CDATA[serverless]]></category><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sat, 05 Jun 2021 04:06:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654315752890/1WOP7KWTF.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Earlier this year(2021), I worked on <a target="_blank" href="https://www.venturebites.co/">Venturebites</a> with a friend, which is a portal for tech startup events in Asia.</p>
<p>I was actively working on it for 2 months to get the system up and running. As of today, it is not under active development.</p>
<p>Here are some screen captures:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654394271704/MEOxsIoKj.png" alt="venturebites home page" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654394618921/f0R9sqNSL.png" alt="venturebites home page 2" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654394773370/KVA9mSvFG.png" alt="venturebites home page 3" /></p>
<h2 id="heading-how-venturebites-started">How venturebites started</h2>
<p>I was approached by a friend who shared the idea of aggregating all things related to tech startups in a single portal, starting with an events directory. This will greatly alleviate the pains of having to visit multiple websites just to keep up to date on events related to tech startups in Asia.</p>
<p>Indeed, we live in a world where we are simply spoilt for choices that we "don't know what to choose", ending up in analysis paralysis.</p>
<p>Being a tech guy, I did not think too much of the business model but thought of it as an interesting opportunity to put some skills into practice while trying out new technology.</p>
<p>From the events side, we have <a target="_blank" href="https://www.eventbrite.com/">Eventbrite</a>, <a target="_blank" href="https://www.techinasia.com/events/live">TechInAsia</a>, <a target="_blank" href="https://e27.co/events/">e27</a>, and many more.</p>
<h2 id="heading-system-architecture">System architecture</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654395415530/D4lXcJrtP.png" alt="venturebites system architecture" /></p>
<p>This is the architecture of Venturebites, which is quite simple.</p>
<p>On the backend, there is a background job that runs on a schedule on my machine, and an API service that serves queries. Both of them are built with typescript, on node.js.</p>
<p>This is deployed through <a target="_blank" href="https://www.serverless.com/">serverless framework</a>, which takes care of creating the necessary AWS resources.</p>
<p>On the frontend, there is a website/web app for people to view events, built with <a target="_blank" href="https://nextjs.org/">next.js</a>(react). This is deployed through <a target="_blank" href="https://vercel.com/">Vercel</a>, because it is a sponsor of next.js, and therefore has a smooth native deployment workflow.</p>
<h2 id="heading-whats-difficult-1-data-extraction-and-unification">What's difficult 1: data extraction and unification</h2>
<p>Even though this is a simple system, the process of gathering data from various sources and streamlining them into a unified format is tedious, and this will only get worse over time.</p>
<p>So far, I have integrated just 3 sources and am beginning to experience the mental overhead of managing the data.</p>
<p>But here's where a statically typed programming language really shines. By spending a little effort to define the data format of each source upfront, I have an idea of the data shape and can focus on consolidating them into a single destination format instead of having to do guesswork on all of them.</p>
<h2 id="heading-whats-difficult-2-time-zone-and-offsets">What's difficult 2: Time zone and offsets</h2>
<h3 id="heading-e27">E27</h3>
<p>For e27, there is an API to retrieve events and another API to retrieve event detail. The challenge is in getting the right UTC offset, because the data isn't super clean.</p>
<p>Here's what an event looks like:</p>
<pre><code>{
  <span class="hljs-attribute">datestart</span>: <span class="hljs-string">"2021-02-03 13:00:00"</span>,
  <span class="hljs-attribute">dateend</span>: <span class="hljs-string">"2021-02-05 09:00:00"</span>,
  <span class="hljs-attribute">timezone</span>: <span class="hljs-string">"(GMT+08:00) Kuala Lumpur, Singapore"</span>
  <span class="hljs-comment">// some other fields</span>
}
</code></pre><p>If I remember correctly, the timezone of the datetime is stored according to the event's location. Anyone viewing that event outside that timezone will see the wrong time.</p>
<p>Some processing needs to be done to extract the "+08:00" from <code>timezone</code>, and convert it into minutes.</p>
<p>If I want to work with the actual time zone string, more work has to be done because there are various forms that <code>timezone</code> can take.</p>
<p>Some examples are <code>(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi</code>, <code>(GMT-08:00) Pacific Time (US &amp; Canada)</code>.</p>
<p>After sorting out the event data, I used the event detail API to gather the remaining data such as location, targeted industries.</p>
<h4 id="heading-thoughts-on-e27s-api">Thoughts on E27's API</h4>
<p>In summary, E27's data isn't the nicest to work with because the data returned by their API is formatted according to how the frontend will display it, i.e. the backend and frontend are tightly coupled.</p>
<p>This is effective in terms of their implementation effort, but poor in terms of maintaining the system and opening up the API to third-party developers.</p>
<p>As a developer, what I would like to see is the datetime returned in <a target="_blank" href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601 format</a>, which the frontend can use to display it in the user's timezone.</p>
<p>Even better, the API can return the <a target="_blank" href="https://en.wikipedia.org/wiki/Tz_database">IANA timezone</a> data directly, which is used to infer the UTC offset. This is important for countries that practise <a target="_blank" href="https://en.wikipedia.org/wiki/Daylight_saving_time">Daylight Saving Time(DST)</a>. Using an offset is acceptable in many cases, but fails when DST kicks in, or in the rare case when a country/city decides to changes its timezone.</p>
<p>Check out this <a target="_blank" href="https://www.youtube.com/watch?v=-5wpm-gesOY&amp;t=520s&amp;ab_channel=Computerphile">youtube video</a> and <a target="_blank" href="https://stackoverflow.com/tags/timezone/info">stackoverflow</a> to learn about the difference between offset and timezone.</p>
<h3 id="heading-techinasia">TechInAsia</h3>
<p>TechInAsia's API is much easier to work with, regarding the management of timezone and offset.</p>
<p>Also, the data for the event and event detail are available in the same API, which may or may not be good from a technical perspective, but is certainly useful for the consumer.</p>
<p>Here's what an event looks like:</p>
<pre><code>{
  <span class="hljs-keyword">event</span>\_start\_dt\_utc\_tz: <span class="hljs-string">"20210224T080000Z"</span>,
  <span class="hljs-keyword">event</span>\_end\_dt\_utc\_tz: <span class="hljs-string">"20210224T090000Z"</span>,
  <span class="hljs-keyword">event</span>\_duration\_date\_sgt: <span class="hljs-string">"Wednesday, 24 February 2021"</span>,
  <span class="hljs-keyword">event</span>\_duration\_time\_sgt: <span class="hljs-string">"4:00PM to 5:00PM (GMT+8)"</span>,
  <span class="hljs-comment">// some other fields</span>
}
</code></pre><p>It returns both the local and UTC time. The UTC time can be easily formatted according to users' timezone.</p>
<h4 id="heading-thoughts-on-techinasias-api">Thoughts on TechInAsia's API</h4>
<p>It is a pleasant experience using their API, because it is well designed.</p>
<h3 id="heading-sginnovate">SGInnovate</h3>
<p>Retrieve events data from SGInnovate is the toughest of the 3 sources because there is no public API.</p>
<p>Instead, data has to be scraped from the html source. While webscraping is flexible - we can get almost any data we want, it is brittle. I used <a target="_blank" href="https://github.com/puppeteer/puppeteer">puppeteer</a>, a headless chrome API, to scrape the data.</p>
<p>Here's what an event look like:</p>
<pre><code>{
  <span class="hljs-attribute">startDate</span>: <span class="hljs-string">"Wednesday, January 13, 2021"</span>,
  endDate: <span class="hljs-string">"Thursday, January 14, 2021"</span>,
  // some other fields
}
</code></pre><p>After retrieving the event data which contains only the date, I visit the event detail page to extract the time and offset, which looks something like:</p>
<pre><code>{
  <span class="hljs-attribute">startTime</span>: <span class="hljs-string">"11:00AM"</span>,
  endTime: <span class="hljs-string">"12:00PM"</span>,
  utcOffset: <span class="hljs-string">"+8"</span>
}
</code></pre><p>Turns out that the way SGInnovate manage timezone and offset is similar to e27.</p>
<h4 id="heading-thoughts-on-sginnovates-scraping">Thoughts on SGInnovate's scraping</h4>
<p>This is the most tedious of all, because there is no real-time feedback from web scraping, unlike an API call that returns after 1 second.</p>
<p>It easily takes anywhere from 10 to 30 seconds just to get the first page of events. Then I need to inspect the HTML element to find the correct tags to extract the relevant data, <code>console.log</code> it out to check whether it worked.</p>
<p>Worst of all, I found that there are at least 4 variations of the HTML layout in the event detail page, which greatly disrupted my effort to extract the UTC offset.</p>
<p>I only managed to retrieve 14 out of 47 events data for 2021. After some more hours of tinkering, I gave up and moved on.</p>
<p>If anyone is adventurous and kind enough to help, please let me know.</p>
<h2 id="heading-frontend">Frontend</h2>
<p>I am not a frontend guy, but have worked with react, redux, and a little on react native. I chose next.js because it is suitable for creating <a target="_blank" href="https://nextjs.org/docs/basic-features/pages#two-forms-of-pre-rendering">hybrid website/web app</a>, which is related to static server-side generation and dynamic server-side rendering.</p>
<h3 id="heading-static-vs-server-side-generation">Static vs server-side generation</h3>
<p>This topic of <a target="_blank" href="https://betterprogramming.pub/server-side-rendering-vs-static-site-generation-53a34872728c">static generation vs server side generation</a> has got me confused for a long time.</p>
<p>In short, server-side generation is what we think of as the old-school way of building websites. Each page request causes the server to dynamically render the page, and the browser performs a full refresh.</p>
<p>Static generation is still server-side generation, but it is done at <strong>build time</strong>, instead of run time. This is the method used for websites built on <a target="_blank" href="https://jamstack.org/">JAMstack</a>.</p>
<p>With react, however, we can combine the best of both worlds, which is what next.js provides!</p>
<h3 id="heading-ui-library">UI library</h3>
<p>I tried <a target="_blank" href="https://chakra-ui.com/">Chakra UI</a>, which is designed with composability, accessibility, and great developer experience in mind.</p>
<p>Out of all the UI libraries I have used(bootstrap, ant design, tailwind), I like Chakra the best.</p>
<p>Regarding CSS modules and CSS in JS(styled components), I originally liked the idea of styled components, being able to compose layered components, but never using it to the point of feeling productive.</p>
<p>After some time, I switched over to CSS module, and managing CSS became a simple task of isolating the styles for each file.</p>
<h3 id="heading-data-fetching">Data fetching</h3>
<p>The data management layer is the meat of all frontend SPA.</p>
<p>I am fairly comfortable with redux and redux saga, but decided to try out <a target="_blank" href="https://swr.vercel.app/">swr</a>, a hook for data fetching, which offers built-in cache, automatic refetching, and deduplication.</p>
<p>It is easy to use, but I did not find a clean way to manage the code.</p>
<p>Here's what the data fetching for infinite scrolling look like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {
    <span class="hljs-attr">size</span>: ongoingEventPage,
    <span class="hljs-attr">setSize</span>: setOngoingEventPage,
    <span class="hljs-attr">data</span>: ongoingResult,
    <span class="hljs-attr">error</span>: ongoingError,
    <span class="hljs-attr">isLoading</span>: ongoingIsLoadingInitial,
  } = useEventsInfinite(ongoingEventQuery());

  <span class="hljs-keyword">const</span> ongoingIsLoadingMore = isLoadingMore(
    ongoingIsLoadingInitial,
    ongoingEventPage,
    ongoingResult
  );
  <span class="hljs-keyword">const</span> lastFetchedOngoingEventResult = lastFetchedResult(ongoingResult);
  <span class="hljs-keyword">const</span> {
    <span class="hljs-attr">count</span>: ongoingEventsCount,
    <span class="hljs-attr">data</span>: lastFetchedOngoingEvents,
    <span class="hljs-attr">hasNextPage</span>: hasMoreOngoingEvents,
  } = lastFetchedOngoingEventResult;

  <span class="hljs-keyword">const</span> ongoingEvents: any\[\] = \[\];
  ongoingResult?.forEach(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!justMounted) {
      <span class="hljs-keyword">if</span> (ongoingEvents.length === <span class="hljs-number">0</span>) {
        sendGAEvent(GAEvents.EventSearch, {
          <span class="hljs-attr">eventSearch</span>: {
            ...ongoingEventQuery(),
            <span class="hljs-attr">page</span>: <span class="hljs-number">1</span>,
          },
        });
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ongoingEvents.length &gt; <span class="hljs-number">0</span>) {
        sendGAEvent(GAEvents.EventSearchLoadMore, {
          <span class="hljs-attr">eventSearch</span>: {
            ...ongoingEventQuery(),
            <span class="hljs-attr">page</span>: ongoingEventPage,
          },
        });
      }
    }
    justMounted = <span class="hljs-literal">false</span>;
    ongoingEvents.push(...result?.payload?.data);
  });
</code></pre>
<p>The functions referenced from above are defined as follow:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useEventsInfinite = <span class="hljs-function">(<span class="hljs-params">query: Record&lt;string, any&gt;</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { data, error, size, setSize } = useSWRInfinite(
    (page: number): <span class="hljs-function"><span class="hljs-params">string</span> =&gt;</span> {
      query.page = page + <span class="hljs-number">1</span>;
      <span class="hljs-keyword">const</span> url = \<span class="hljs-string">`<span class="hljs-subst">${BASE\_URL}</span>/events/?<span class="hljs-subst">${querystring.stringify(query)}</span>\`;
      return url;
    },
    fetcher
  );
  return { data, size, setSize, error, isLoading: !error &amp;&amp; !data };
};

export const fetcher = (url: string) =&gt; fetch(url, { headers }).then((r) =&gt; r.json());

export const isLoadingMore = (
  isLoading: boolean,
  page: number,
  result: any\[\] | undefined
): boolean =&gt; {
  return (
    isLoading || (page &gt; 0 &amp;&amp; result?.\[page - 1\]?.payload?.data === undefined)
  );
};

export const lastFetchedResult = (result: any\[\] | undefined): any =&gt; {
  return result?.\[result?.length - 1\]?.payload || {};
};</span>
</code></pre>
<p>Not sure what you think, but this is a monstrosity of a quick hack that is put together just to "make things work". It is totally possible that I am using SWR wrongly, and there is a much cleaner way of doing things.</p>
<p>Besides CSS, data fetching is one of the major reasons why frontend development is so complicated, and there is no easy way out.</p>
<p>One could go the redux way, which offers a well-defined data workflow but have to write tons of boilerplate code and handle normalisation of data, and other out-of-the-box features that SWR or other built-in cache libraries offer.</p>
<h2 id="heading-data-integration-is-tough">Data integration is tough</h2>
<p>Now, come to think of it, I have great admiration for the work that big data integrators like <a target="_blank" href="https://segment.com/">segment</a>, <a target="_blank" href="https://zapier.com/">zapier</a>, have done. I cannot imagine how much effort it takes just to maintain the system's reliability and uptime.</p>
<p>This speaks to the fact that real-world data is always messy, some more than others.</p>
<p>But data is all around us. Those who can gather data of disparate forms, make sense of it, and provide value to others will stay ahead.</p>
]]></content:encoded></item><item><title><![CDATA[Managing personal finance]]></title><description><![CDATA[Personal finance is boundless. Whether it is optimising expenses, savings, investments, all the way to FIRE, there is always something interesting to talk…]]></description><link>https://yaphc.com/managing-personal-finance</link><guid isPermaLink="true">https://yaphc.com/managing-personal-finance</guid><category><![CDATA[personal finance]]></category><category><![CDATA[finance]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Tue, 18 May 2021 06:42:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654330073656/JxoWS4L4m.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Personal finance is boundless. Whether it is optimising expenses, savings, investments, all the way to <a target="_blank" href="https://www.investopedia.com/terms/f/financial-independence-retire-early-fire.asp">FIRE</a>, there is always something interesting to talk about.</p>
<p>As an analytical person, I like to track my financial situation to see how it changes every month.</p>
<blockquote>
<p>You Can’t Manage What You Don’t Measure</p>
</blockquote>
<h2 id="heading-tracking-expenses">Tracking expenses</h2>
<p>Without knowing much about personal finance at all, I started off by creating a simple monthly expense spreadsheet back in 2019, a few months before I started full-time work. It is really as simple as it can get.</p>
<p>Why not use an expense tracking app, or better, build one myself like a true techie would?</p>
<p>Because I just want to get started and I only need to know how much I spend every month. I don't need a data analysis pipeline, expense item categorization, or a nice-looking interface.</p>
<p><strong>Monthly expenses</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322219795/XyvaFvMn2.png" alt="may-2021-expenses.png" /></p>
<p>For monthly expenses, I broke it down by monthly recurring expenses such as transport, bills, insurance premiums and individual expenses.</p>
<p>There is a category column to display the total sum of each category.</p>
<p>The "<strong>Total</strong>" will be used to calculate the ratio of spending vs saving in another spreadsheet.</p>
<h2 id="heading-tracking-income-breakdown">Tracking income breakdown</h2>
<p>After getting my expenses down, the next step is to get an overview of the allocation of my monthly income - What proportion of the income is spent and saved</p>
<p><strong>General breakdown of monthly income allocation</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322334902/7_Ivg8Zrj.png" alt="monthly-income-general-breakdown.png" /></p>
<p>This sheet shows the general breakdown of the proportion of income saved, used for personal expenses and total expenses.</p>
<p>The cells in blue contain formula that will calculate its value based on other fields.</p>
<p>Here, the values are taken from another sheet called "<strong>detailed breakdown</strong>".</p>
<p><strong>Detailed breakdown of monthly income allocation</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322373580/remt0I_Va.png" alt="monthly-income-detailed-breakdown.png" /></p>
<p>This sheet is the detailed breakdown of my monthly income allocation. The "<strong>My expenses</strong>" column is taken from the monthly expenses sheet in the section above.</p>
<p>Here, I have columns for other expenses such as parents' allowance and study loan.</p>
<p><strong>Study loan</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322411783/Gbq1H83g9.png" alt="monthly-income-loans.png" /></p>
<p>I also have a sheet to track my study loan repayment using.</p>
<h2 id="heading-tracking-investment-portfolio">Tracking investment portfolio</h2>
<p>With the expenses and savings portion out of the way, let's move on to the more exciting stuff - the investment portfolio!</p>
<p>I am a novice when it comes to investment. I dipped my toes into the world of stocks in 2020 May, and have little to no clue as to what I am doing.</p>
<p>Still, I wanted a simple way to track my portfolio without spending weeks or months trying to reinvent the wheel.</p>
<p>A quick search on google brought me to this incredible <a target="_blank" href="https://investmentmoats.com/stock-market-commentary/portfolio-management/introducing-our-free-stock-portfolio-tracker-spreadsheet/">stocks portfolio tracker</a> by Kyith Ng.</p>
<p>It has exactly what I need. I am able to list down the stocks that I want to track, enter the transactions, and look at the P&amp;L of my portfolio.</p>
<p>It supports transactions in 3 currencies - SGD, USD, HKD.</p>
<h2 id="heading-tracking-net-worth">Tracking net worth</h2>
<p>Aftter handling my savings, expenses, stocks portfolio, the last piece of the finance tracking puzzle is to track my net worth over time.</p>
<p>Once again, Kyith saves the day with his powerful <a target="_blank" href="https://investmentmoats.com/wealth-building-2/dont-track-your-expenses-or-budget-first-plot-your-net-worth-instead/">networth spread sheet</a>.</p>
<p>The idea is to gather all your accounts(business, cash, investment) in one place, aggregate them and track how it changes over time.</p>
<p><strong>Track the value of all accounts in one place</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322551949/V76Ksatl1.png" alt="networth-current-account-view.png" /></p>
<p><strong>Summary of accounts</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322603951/aKZvHT0jv.png" alt="networth-current-account-view-2.png" /></p>
<p>In this <strong>history</strong> sheet, the values are taken from the <strong>summary</strong> section in the <strong>current account view</strong> sheet.</p>
<p><strong>Track changes in networth every month</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322663642/JTu2WJeB1.png" alt="networth-history.png" /></p>
<p>Finally, there is a <strong>charts</strong> sheet to visualise the networth over time, which is a fun way to keep things interesting.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654324631565/BL6GFhvL3.png" alt="networth-chart.png" /></p>
<h2 id="heading-tracking-portfolio-alternative-investingnote">Tracking portfolio alternative: InvestingNote</h2>
<p><a target="_blank" href="https://www.investingnote.com/">InvestingNote</a> is an investment community that offers stocks portfolio tracking, charts, stocks screener, general chat and interest groups.</p>
<p>I mainly use it for portfolio tracking, and interest group discussion, that's about all.</p>
<p>One cool feature that I discovered recently is the <a target="_blank" href="https://www.investingnote.com/stock_events/calendar">stocks calendar</a>. It shows a list of corporate events such as dividend schedules, financial result reports, etc.</p>
<p>In my opinion, the community is useful for casual chats, sharing of ideas. As with social media outlets, a large proportion of the user-generated content won't be useful to any particular individual.</p>
<h2 id="heading-tracking-portfolio-alternative-stockscafe">Tracking portfolio alternative: StocksCafe</h2>
<p>More recently, I discovered <a target="_blank" href="https://stocks.cafe/">StocksCafe</a>, a portfolio tracker developed by <a target="_blank" href="https://evankoh.com/">Evan Koh</a>. It is an all-in-one platform that tracks your stocks and options performance, asset allocation, dividends, news.</p>
<p><strong>Portfolio page</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654324697040/qgKFgCKEk.png" alt="stocks-cafe-portfolio.png" /></p>
<p>Of course, there is also just as much useful information for individual stocks.</p>
<p><strong>Info on individual stocks</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654324729517/10bpBKr7X.png" alt="stocks-cafe-stock-info.png" /></p>
<p>If you are looking for inspiration, there is a shared stock screener and portfolio tool that allows you to see the public screeners and portfolios of other users.</p>
<p><strong>Shared portfolios</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654324761770/xuVvPCjGM.png" alt="stocks-cafe-shared-portfolios-1.png" /></p>
<p>One cool feature of StocksCafe is the personalised feed, which consists of a daily summary of your portfolio, activities of people that you follow, news on trending and popular stocks.</p>
<p><strong>Personal wall</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654322149179/I02gI8sUZ.png" alt="stocks-cafe-wall.png" /></p>
<p>When it comes to using a product, and deciding whether to make a purchase, one of the top indicators of consumer confidence is the founder's investment in their own product.</p>
<p>Evan is very active on the platform. He has put in place a roadmap, feature requests, and bug fixes so that StocksCafe can grow together with its users.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654324822090/oGg3AtgAA.png" alt="stocks-cafe-friends-access-1.png" /></p>
<p>StocksCafe is free to use, and offers a membership option for full access to the platform. .</p>
<p>With just the features mentioned above, the membership fee is really a steal. As a software engineer, I feel that the amount of work it takes to build and maintain this platform justifies a higher price point.</p>
<p>Even if the price were to double, I will still gladly pay for it, knowing that the platform is here to stay for a good period of time.</p>
<p><strong>Affordable membership fee</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654324850170/2Mz4l-dgp.png" alt="stocks-cafe-friends-fee.png" /></p>
<p>Finally, if you want to give StocksCafe a try, you can sign up with my <a target="_blank" href="https://stocks.cafe/user/tosignup?referral_code=Oh7uq03">referral link</a> to enjoy all the features for 2 months. If you are happy with StocksCafe and decide to purchase the membership, I will receive 20% of the fee at no additional cost to you.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Managing finance is not easy, but it does not have to be complicated.</p>
<p>With a little research on how other finance enthusiasts manage their money, we can come up with a simple system to do the same for ourselves.</p>
]]></content:encoded></item><item><title><![CDATA[Data mining: SQL for data practitioners]]></title><description><![CDATA[Data practitioners use SQL for data mining: From simply displaying data to telling stories with data. As a software engineer, most of my interactions with…]]></description><link>https://yaphc.com/data-mining-sql-for-data-practitioners</link><guid isPermaLink="true">https://yaphc.com/data-mining-sql-for-data-practitioners</guid><category><![CDATA[SQL]]></category><category><![CDATA[database]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Mon, 19 Apr 2021 08:09:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654330156162/DOjWwXjHm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Data practitioners use SQL for data mining: From simply displaying data to telling stories with data.</p>
<p>As a software engineer, most of my interactions with SQL are for simple <a target="_blank" href="https://en.wikipedia.org/wiki/Online_transaction_processing">transactional queries</a>, rather than <a target="_blank" href="https://en.wikipedia.org/wiki/Online_analytical_processing">analytical queries</a>.</p>
<p>The main difference between them is that transactional queries are usually simple and involves a few JOINs because they are meant to serve live user requests, while analytics queries are more complex and computationally intensive.</p>
<h2 id="heading-practical-sql">Practical SQL</h2>
<p>I wanted to learn more about the analytic side of things with SQL, beyond the <code>SELECT</code>, <code>WHERE</code>, <code>GROUP BY</code>, <code>JOIN</code>, and came across the book <a target="_blank" href="https://www.amazon.sg/Practical-Sql-Beginners-Guide-Storytelling/dp/1593278276">Practical SQL</a>, which provides a great foundation in SQL.</p>
<p>It is written by Anthony DeBarros, a data analyst and journalist, who uses SQL(PostgreSQL) to supercharge his storytelling abilities.</p>
<p>Anthony goes through the problem-solving processes of acquiring and analysing data using real-world datasets and scenarios such as U.S. Census demographics, crime statistics, and data about taxi rides in New York City.</p>
<p>This book is a great read for people who work with data or looking to get into such roles. It is useful even for non-technical people such as business analysts, marketing managers, and C-level executives.</p>
<h2 id="heading-outstanding-chapters">Outstanding chapters</h2>
<p>While the the entire book is a great read, there are a few chapters that stood out to me, as these cover the topics that I wanted to learn.</p>
<h3 id="heading-chaper-10-statistical-functions-in-sql">Chaper 10: Statistical functions in SQL</h3>
<p>This chapter explains the concept and usefulness of <a target="_blank" href="https://www.postgresql.org/docs/current/tutorial-window.html">window functions</a> to perform calculations across groups of data.</p>
<p>This is similar to <code>GROUP BY</code>, with one important difference that the rows are not grouped into a single output row. Instead, each row of the group is available for processing.</p>
<p>Let's take an example of an employee table, from PostgreSQL's website, which contains the department, employee number, and salary. The <code>rank()</code> is used to produce a numerical rank of the salary of each employee by the department.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654330335941/r2WCWl_s-.png" alt="employee-rank-query.png" /></p>
<p>With <code>GROUP BY</code> department, we can use aggregate functions to compute a single value from the grouped rows, but unable to access each individual row.</p>
<h3 id="heading-chapter-13-mining-text-to-find-meaningful-data-full-text-search-in-postgresql">Chapter 13: Mining text to find meaningful data - Full text search in PostgreSQL</h3>
<p>The chapter introduces <a target="_blank" href="https://en.wikipedia.org/wiki/Full-text_search">full-text search</a> capabilities in PostgreSQL. The general idea is to store the text that we want to search for as a list of <a target="_blank" href="https://en.wikipedia.org/wiki/Lexeme">lexemes</a>, and query for the text by transforming it to lexeme before matching against the <a target="_blank" href="https://en.wikipedia.org/wiki/Inverted_index">inverted index</a>.</p>
<p>I was particularly interested in full-text search as it is one of the first few domain areas that I worked on as a software engineer and enjoyed very much, which is described in <a target="_blank" href="https://www.yaphc.com/first-software-engineering-role-review">my first software engineering role</a> and <a target="_blank" href="https://www.yaphc.com/pagination-deceptively-simple-task">pagination: the deceptively simple task</a>.</p>
<p><strong>Basic full text search</strong></p>
<p><a target="_blank" href="https://www.postgresql.org/docs/current/datatype-textsearch.html">tsvector</a> is the data type that represents a sorted list of lexemes.</p>
<pre><code><span class="hljs-keyword">SELECT</span> to_tsvector(<span class="hljs-string">'I am walking across the sitting room to sit with you.'</span>);
→ <span class="hljs-string">'across'</span>:<span class="hljs-number">4</span> <span class="hljs-string">'room'</span>:<span class="hljs-number">7</span> <span class="hljs-string">'sit'</span>:<span class="hljs-number">6</span>,<span class="hljs-number">9</span> <span class="hljs-string">'walk'</span>:<span class="hljs-number">3</span>
</code></pre><p><a target="_blank" href="https://www.postgresql.org/docs/current/datatype-textsearch.html">ts_query</a> is the data type that represents a full text search query as a list of lexemes.</p>
<pre><code><span class="hljs-keyword">SELECT</span> to_tsquery(<span class="hljs-string">'walking &amp; sitting'</span>);
→ <span class="hljs-string">'walk'</span> &amp; <span class="hljs-string">'sit'</span>
</code></pre><p>To perform a full text query, we can use the '<code>@@</code>' operator</p>
<pre><code><span class="hljs-keyword">SELECT</span> to_tsvector(<span class="hljs-string">'I am walking across the sitting room'</span>) @@ to_tsquery(<span class="hljs-string">'walking &amp; sitting'</span>);
→ <span class="hljs-keyword">true</span>
</code></pre><p><strong>Showing results fragment relative to query</strong></p>
<p>Apart from text matches, we can also show fragments of the search results that relate to the search term with <code>ts_headline</code>.</p>
<pre><code><span class="hljs-keyword">select</span> president, speech_date,
ts_headline(speech_text, to_tsquery(<span class="hljs-string">'Vietnam'</span>),
 <span class="hljs-string">'StartSel = &lt;,
 StopSel = &gt;,
 MinWords=5,
 MaxWords=7,
 MaxFragments=1'</span>)
<span class="hljs-keyword">from</span> "practical-sql".<span class="hljs-built_in">public</span>.president_speeches ps
<span class="hljs-keyword">WHERE</span> search_speech_text @@ to_tsquery(<span class="hljs-string">'Vietnam'</span>);
</code></pre><p>Note that <code>speech_text</code> is text type, not <code>tsvector</code> type, while search_speech_text is <code>tsvector</code> type.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654330356485/ukwqo_sUSU.png" alt="ts_headline-query.png" /></p>
<p><strong>Distance operator</strong></p>
<p>We can query documents with search terms that are close to one another using the <code>&lt;-&gt;</code> operator. A number can be used in place of the hyphen to indicate the distance between the search terms.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> president,
speech_date,
ts_headline(speech_text, to_tsquery(<span class="hljs-string">'military &lt;-&gt; defense'</span>),
 <span class="hljs-string">'StartSel = &lt;,
 StopSel = &gt;,
 MinWords=5,
 MaxWords=7,
 MaxFragments=1'</span>)
<span class="hljs-keyword">FROM</span> president_speeches
<span class="hljs-keyword">WHERE</span> search_speech_text @@ to_tsquery(<span class="hljs-string">'military &lt;-&gt; defense'</span>);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654330254623/baDjNo9PV.png" alt="distance-operator.png" /></p>
<p><strong>Ranking search results</strong></p>
<p>Finally, we can also rank the search results by relevance with <code>ts_rank</code> and <code>ts_rank_cd</code>.</p>
<p>The difference between them is that <code>ts_rank</code> ranks the results based on how often the search terms appear in the text, while <code>ts_rank_cd</code> ranks the results based on the proximity of the search terms to each other.</p>
<h3 id="heading-chapter-15-view-functions-triggers">Chapter 15: View, functions, triggers</h3>
<p>One of the principles of software development is to keep the things <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> while automating processes.</p>
<p><strong>Views</strong></p>
<p>A <a target="_blank" href="https://www.postgresql.org/docs/current/sql-createview.html">view</a> is a <strong>virtual</strong> table that is created using a saved query, which is run <strong>every time</strong> the view is accessed. Note that it does not save the result of a query, which is what <a target="_blank" href="https://www.postgresql.org/docs/current/rules-materializedviews.html">materialized view</a> does.</p>
<p>Main benefits of using a view:</p>
<ul>
<li>Avoid code duplication</li>
<li>Reduce complexity in nested queries</li>
<li>Provide security by limiting access to only certain columns in a table</li>
</ul>
<p>We can also insert, update, delete a row from a view, and the underlying table will be updated too because a view is created from a saved query that is run every time it is accessed.</p>
<p><strong>Functions</strong></p>
<p>We can use <a target="_blank" href="https://www.postgresql.org/docs/current/sql-createfunction.html">functions</a> to simplify query, update table, or use it as a response to events(trigger)</p>
<p><strong>Trigger</strong></p>
<p><a target="_blank" href="https://www.postgresql.org/docs/current/sql-createtrigger.html">Triggers</a> allow us to automate workflows whenever events happen, such as saving a log of changes made to a table.</p>
<p>It can be configured to fire on <code>INSERT</code>/<code>UPDATE</code>/<code>DELETE</code>/<code>TRUNCATE</code> events, before or after it happens, once per row or one per entire operation.</p>
<p>Using the example in the book, we can create a <strong>trigger function</strong> that logs grades change for students.</p>
<pre><code><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR REPLACE</span> <span class="hljs-keyword">FUNCTION</span> record_if_grade_changed()
<span class="hljs-keyword">RETURNS</span> <span class="hljs-type">trigger</span> <span class="hljs-keyword">AS</span>
$$<span class="pgsql">
<span class="hljs-keyword">BEGIN</span>
<span class="hljs-keyword">IF</span> <span class="hljs-built_in">NEW</span>.grade &lt;&gt; <span class="hljs-built_in">OLD</span>.grade <span class="hljs-keyword">THEN</span>
    <span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> grades_history (
    student_id,
    course_id,
    change_time,
    course,
    old_grade,
    new_grade
    )
    <span class="hljs-keyword">VALUES</span>
    (<span class="hljs-built_in">OLD</span>.student_id,
    <span class="hljs-built_in">OLD</span>.course_id,
    now(),
    <span class="hljs-built_in">OLD</span>.course,
    <span class="hljs-built_in">OLD</span>.grade,
    <span class="hljs-built_in">NEW</span>.grade);
<span class="hljs-keyword">END</span> <span class="hljs-keyword">IF</span>;
<span class="hljs-keyword">RETURN</span> <span class="hljs-built_in">NEW</span>;
<span class="hljs-keyword">END</span>;
$$</span> <span class="hljs-keyword">LANGUAGE</span> plpgsql;
</code></pre><p>Next, create the <strong>trigger</strong></p>
<pre><code>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TRIGGER</span> grades_update
<span class="hljs-keyword">AFTER</span> <span class="hljs-keyword">UPDATE</span>
<span class="hljs-keyword">ON</span> grades
<span class="hljs-keyword">FOR</span> <span class="hljs-keyword">EACH</span> <span class="hljs-keyword">ROW</span>
<span class="hljs-keyword">EXECUTE</span> <span class="hljs-keyword">PROCEDURE</span> record_if_grade_changed();
</code></pre><p>Now, the function <code>record_if_grade_changed</code> will run after the <code>grades</code> table is updated each time.</p>
<h2 id="heading-closing">Closing</h2>
<p>SQL is an essential tool in every data professional's arsenal of technologies. I highly recommend giving <a target="_blank" href="https://www.amazon.sg/Practical-Sql-Beginners-Guide-Storytelling/dp/1593278276">Practical SQL</a> a try, whether it is an introduction or a refresher.</p>
]]></content:encoded></item><item><title><![CDATA[Tracking user behaviour with Google Analytics and Google Tag Manager]]></title><description><![CDATA[Building a great product is important, but tracking its impact on end-users is even more important in order to determine its effectiveness. Being a…]]></description><link>https://yaphc.com/tracking-user-behaviour-google-analytics-and-google-tag-manager</link><guid isPermaLink="true">https://yaphc.com/tracking-user-behaviour-google-analytics-and-google-tag-manager</guid><category><![CDATA[Next.js]]></category><category><![CDATA[React]]></category><category><![CDATA[Google Analytics]]></category><category><![CDATA[google tag manager]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Fri, 19 Mar 2021 08:21:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654330420696/3HQDjc7r9.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Building a great product is important, but tracking its impact on end-users is even more important in order to determine its effectiveness.</p>
<p>Being a software developer means that I spend most of my time writing code to build and maintain features, and fix bugs that are uncovered along the way.</p>
<p>I wanted to gain first-hand experience in setting up simple analytics to track custom events in order to understand user behaviour. What better tool to start with than the ubiquitous <a target="_blank" href="https://analytics.google.com/analytics/web/">Google Analytics</a>? I chose <a target="_blank" href="https://yaphc.com/project-venturebites-a-portal-for-asia-tech-startup-events">Venture bites</a> for this experiment.</p>
<h2 id="heading-set-up-google-analytics">Set up Google Analytics</h2>
<p>First, create a Google Analytics(GA) account, property, view.</p>
<p>Then, create a GA <strong>tracking code</strong> under <strong>property.</strong> It starts with '<strong>UA</strong>'.</p>
<p>Finally, we just need to paste the provided code snippet in every web page that we want to track.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654392421823/8WSZbKF3f.png" alt="GA tracking code" /></p>
<p>Where to find tracking code: <strong>Admin</strong> -&gt; <strong>property</strong> -&gt; <strong>tracking code</strong></p>
<p>That's all!</p>
<p>By default, that piece of code only tracks page view, which is fine. But, we also want to track custom events too.</p>
<h2 id="heading-google-analytics-with-single-page-application">Google Analytics with Single Page Application</h2>
<p>Furthermore, if our website/webapp is a <a target="_blank" href="https://en.wikipedia.org/wiki/Single-page_application">Single Page Application</a>, only the first page load will trigger the page view event because GA event is only triggered when there is a full page load which sends a request to the GA server.</p>
<p>But for a SPA, subsequent page load after the first will not trigger a full page load.</p>
<p>So, we have to set up custom events to tell GA to track them.</p>
<p>Also, I have chosen to use <strong><a target="_blank" href="https://marketingplatform.google.com/about/tag-manager/">Google Tag Manager(GTM)</a></strong> to manage my GA tags. GTM simplify the management of various Google and third party tags.</p>
<h2 id="heading-set-up-google-tag-manager">Set up Google Tag Manager</h2>
<p><strong>1. Create a GA settings variable</strong></p>
<p>This is used to configure GA settings across multiple GA tags.</p>
<p>Paste the GA tracking code in "<strong>Tracking ID</strong>"</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654392613406/7eGAQm4dX.png" alt="Google Tag Manager variable settings" /></p>
<p><strong>2. Create a tag manager account in <a target="_blank" href="https://tagmanager.google.com/#/home">GTM</a>.</strong></p>
<p>Note down the tag ID which starts with '<strong>GTM</strong>'.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654392640233/_YGMbNSiL.png" alt="GTM tags" /></p>
<p>I have 5 tags that track different events.</p>
<p><strong>3. Create a tag configuration</strong></p>
<p>Create a tag configuration for <strong>Google Marketing Platform</strong>, and select the type of event to track(page view, custom event, etc).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654393257857/lAVwBRvIi.png" alt="Google Tag Manager tag configuration" /></p>
<p><strong>4. Create a tag trigger</strong></p>
<p>Create a trigger to let GTM know when to fire a particular event. Afterwards, we can use the <strong>event name</strong> to fire this event.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654393294595/oXB6zLdfu.png" alt="Google Tag Manager tag trigger" /></p>
<p>Trigger for event names starting with 'event-search'</p>
<p><strong>5. Set up event variable</strong></p>
<p>Create a <strong>dataLayer</strong> variable, which we will send from our SPA.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654393345144/UpCyJOx7t.png" alt="Google Tag Manager variable" /></p>
<p>The variable name is "eventSearch"</p>
<p><strong>6. Send custom event in SPA</strong></p>
<p>I use <a target="_blank" href="https://nextjs.org/">Next.js</a> for my SPA, which is based on React.</p>
<p>There are different GTM libraries for React. I chose <a target="_blank" href="https://github.com/alinemorelli/react-gtm">react-gtm</a>.</p>
<p>After setting it up, I discovered another GTM library called <a target="_blank" href="https://github.com/elgorditosalsero/react-gtm-hook">react-gtm-hook</a>, which is based on React hooks and offers a slightly better developer experience. I may try it out in the future to see if it is better.</p>
<p>Side note: I noticed that the "<strong>dataLayer</strong>" data that gets sent to GA contains data from all preceding events, which is a little annoying. I am not sure if this is supposed to happen or if I used it wrongly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654393974326/_uWKkTp5Y.png" alt="Google Tag Manager in React" /></p>
<p><strong>7. Test it in preview</strong></p>
<p>Clicking on the "<strong>preview</strong>" button will bring up a new page that opens up the GA debugger that connects to your website.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654394021666/btJEEjJWD.png" alt="Google tag manager overview" /></p>
<p>Click on <strong>preview</strong> at the top right corner</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654394047705/xDZQHoIbc.png" alt="Google Tag Manager preview" /></p>
<p>Trigger the event on your website, and make sure it appears in the preview window</p>
<p><strong>8. Publish the changes</strong></p>
<p>Remember to hit the <strong>Submit</strong> button. This can be one of the fixes to the problem of "it doesn't work" because we forgot to publish the changes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654394099985/6TKAUUMRq.png" alt="Google Tag Manager publish" /></p>
<p>Workspace changes shows the number of unpublished changes</p>
<p><strong>9. Check GA real-time reports</strong></p>
<p>Finally, to make sure the custom event is set up properly, go to GA <strong>real-time</strong> reports -&gt; <strong>events</strong>. Trigger some events on the website, which should appear in the real-time dashboard after a second or two.</p>
<p>![Google analytics real-time events](https://cdn.hashnode.com/res/hashnode/image/upload/v1654394151788/cqITJmvwq.png align="left"</p>
<p>Events should show up in the real-time dashboard almost immediately</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This is all for the basic setup of tracking a SPA with Google Analytics via Google Tag Manager.</p>
<h2 id="heading-useful-resources">Useful resources</h2>
<p>Learn about Google analytics and Google Tag Manager: <a target="_blank" href="https://analytics.google.com/analytics/academy/">Google analytics academy</a></p>
]]></content:encoded></item><item><title><![CDATA[Instagram scraper: Find viral posts on instagram]]></title><description><![CDATA[In the beginning of 2019, I was experimenting with niche pages on Instagram, and wanted an on-demand tool to find viral instagram posts of users in my…]]></description><link>https://yaphc.com/instagram-scraper-find-viral-posts</link><guid isPermaLink="true">https://yaphc.com/instagram-scraper-find-viral-posts</guid><category><![CDATA[web scraping]]></category><category><![CDATA[instagram]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[side project]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Mon, 31 Aug 2020 09:13:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654332941225/QiEt8mMCS.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the beginning of 2019, I was experimenting with niche pages on Instagram, and wanted an on-demand tool to find viral instagram posts of users in my niche. So, I created a small project to scrape viral posts from any instagram user.</p>
<p>There are various open-source projects such as <a target="_blank" href="https://github.com/dilame/instagram-private-api">instagram-private-api</a> with more features like upload photo/video, manage follower/following, discover trending tags, etc.</p>
<p>For experimenting or automating workflow that requires such features, it is best to use of one these larger projects.</p>
<p>My main goal is to learn the process of inspection of web data, coupled with google search of course, to create a simple <strong>read-only</strong> tool to download best performing posts on instagram.</p>
<h2 id="heading-what-is-a-viral-post">What is a viral post</h2>
<p>The word "viral" hints at what a viral post is. Viral posts are posts that have reached a much larger audience than regular posts. This is the dream of all content creators, marketers, or any creatives who want to grow their audience base.</p>
<p>The challenge is to sample a few viral posts and work backwards to determine what factors contributed to their virality.</p>
<p>While there are no sure ways to make a post go viral, there are guidelines on how to create a <a target="_blank" href="https://www.socialpilot.co/blog/10-types-of-post-for-viral-marketing">viral marketing post</a> in general and <a target="_blank" href="https://whatskatieupto.com/2019/08/how-to-go-viral-on-instagram/">on instagram</a>.</p>
<h2 id="heading-determine-whether-a-post-is-viral">Determine whether a post is viral</h2>
<p>From the engagement perspective, a viral post is one that has significantly higher engagement rate than other posts.</p>
<p>The definition of "significantly higher", "engagement rate" and "other posts" are up to us to decide.</p>
<p>I chose <strong>50%</strong> for "significantly higher", <strong>number of likes</strong> for "engagement rate", and <strong>20 most recent posts</strong> for "other posts".</p>
<p>In short, if a post has 50% more likes than the average number of likes of the 20 most recent posts, it is a viral post.</p>
<p>Of course, this is a naive solution as contextual information such as world and local events are missing.</p>
<h2 id="heading-workflow-to-find-viral-posts-on-instagram">Workflow to find viral posts on instagram</h2>
<ol>
<li>Retrieve user profile</li>
<li>Extract the relevant information using data from the previous step</li>
<li>Retrieve user's media(photo/video uploads)</li>
<li>Calculate the engagement rate of the top 20 most recent posts using data from the previous step</li>
<li>Filter for viral posts using data from step 3 and 4</li>
<li>Save to file</li>
</ol>
<p>In step 1 and 2, we determine <strong>what</strong> information we need and <strong>where</strong> to find them.  </p>
<p>In step 3, we figure out <strong>how</strong> to retrieve user's media by inspecting the HTTP requests.<br />At this point, the bulk of the work on Instagram is done. What is left is to transform the user media data and save it to file.</p>
<p>Step 4, 5, and 6 will be skipped because they are trivial.</p>
<h2 id="heading-1-retrieve-user-profile">1. Retrieve user profile</h2>
<p>The first step is to retrieve information on a user profile, like username, follower count, following count, etc.</p>
<p>Let's use <strong>@9gag</strong> as an example for this exercise.</p>
<p>Go to <a target="_blank" href="https://www.instagram.com/9gag/">https://www.instagram.com/9gag/</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333165896/gBx6zVJc9.png" alt="9gag instagram" /></p>
<p>Fig 1. hmm much posts and followers</p>
<p>Right click on the page and go to "<strong>View page source</strong>", or hit <strong>CTRL + U</strong>. This brings us to the source code 9gag's profile.</p>
<p>To find out where to get the profile information, hit <strong>CTRL+F</strong> and search for "24136", which is the number of posts 9gag has.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333204188/rG4T-IcBU.png" alt="9gag instagram source page" /></p>
<p>Fig 2. found the needle in the sea of gibberish</p>
<p>It looks like we can get some profile information from 9gag's source, but there is also a lot of unrelated data surrounding it.</p>
<p>After spending a few minutes inspecting the file, we can figure out that all information of a user is stored under <code>window._sharedData</code>.</p>
<p><strong>Fig 3. start of the data block</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333245301/eJtU4JpBq.png" alt="9gag instagram shareddata start" /></p>
<p><strong>Fig 4. end of the data block</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333408653/acll1gMBF.png" alt="9gag instagram shareddata end" /></p>
<h2 id="heading-2-extract-the-relevant-information">2. Extract the relevant information</h2>
<p>Now that we have found out the place to look for user information, we need to extract them in order to do useful things.</p>
<p>The part of the data we are interested in is between the <code>{</code> after <code>window._sharedData</code> in Fig 3 and <code>}</code> at the end in Fig 4.</p>
<p>A pattern matching task means regular expression(regex) to the rescue!</p>
<p>Here is the magic pattern in javascript:</p>
<p><code>/window._sharedData = (.*);/</code></p>
<p>To try this out, copy the entire chunk of the <code>window._sharedData,</code> go to <a target="_blank" href="https://regex101.com/">https://regex101.com/</a>, paste it under "test string" and the regex above under "regular expression".</p>
<p>The whole javascript object is matched and we have 9gag's profile information on hand now.</p>
<p><strong>Too much data!</strong></p>
<p>But there is one problem, there is way too much data than we need. To visualise the data better, we can use a <a target="_blank" href="https://jsonformatter.org/json-pretty-print">JSON prettifier</a>.</p>
<p>Copy the entire javascript object, drop it in the json prettifier and click "make pretty".</p>
<p><strong>Fig 5. finally found the data we are after</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333106066/VEabXEM3Q.png" alt="9gag instagram shareddata json prettified" /></p>
<p>It became clear that the data we need is under <code>entry_data.ProfilePage[0].graphql.user</code></p>
<h2 id="heading-3-retrieve-media-uploads">3. Retrieve media uploads</h2>
<p>This is the meat of the entire operation, and requires a little more inspection.</p>
<p>This time we will use the browser's network inspector and instagram's web API. Hit F12 or right click and go to "<strong>Inspect</strong>", select the "<strong>Network</strong>" tab, select "<strong>XHR</strong>" request type.</p>
<p>Still on 9gag's page, scroll down to trigger the spinning loader which will fetch more media. There will be an entry starting with <code>?query_hash=.....</code>. Double click on it and we will see the data for the first page of media.</p>
<p><strong>Fig 6. the request to retrieve user media</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333524773/8Bkoj7QBJ.png" alt="9gag instagram network xhr tab" /></p>
<p><strong>Fig 7. first page of 9gag's media</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333567835/FrY3WVeJG.png" alt="9gag instagram media query first page" /></p>
<p><strong>Deconstructing the media request</strong></p>
<p>The full URL for the media request is <code>https://www.instagram.com/graphql/query/?query_hash=bfa387b2992c3a52dcbe447467b4b771&amp;variables=%7B%22id%22%3A%22259220806%22%2C%22first%22%3A12%2C%22after%22%3A%22QVFCUW0zWkVyMDhkcFlrYTFOeDM1dUU3UF9aM1pmejZDZGVwV0tBTTh0MC1XYnJVY1MxQ21jUE10N21MQUt6V0syM0h4S25Fb1N0R2MxaGxEd3pzcEtNSQ%3D%3D%22%7D</code>.</p>
<p>The URL is unreadable because it is encoded. To decode it, paste it in <a target="_blank" href="https://www.urldecoder.org/">https://www.urldecoder.org/</a> and hit "<strong>decode</strong>", or use the javascript's built-in <strong>decodeURIComponent</strong> function:</p>
<p><code>https://www.instagram.com/graphql/query/?query_hash=bfa387b2992c3a52dcbe447467b4b771&amp;variables={"id":"259220806","first":12,"after":"QVFBRTg2Q2VlUjVFNnBQYzdCUjdSeXM3Z09rVjJCVW9QX1A4U2VQMU55a3dPdmZheEtOUTFrU2h4WTVUSlZRcW5ZV05GbW5BZEJ1YWhQZUZKNlFUd0lrcQ=="}</code></p>
<p>There are 2 important components: <code>query_hash</code> and <code>variables</code>.</p>
<p><code>query_hash</code> determines the type of operation, which in this case is media retrieval.</p>
<p><code>variables</code> is a javascript object which consists of the user id(<code>id</code>), number of media to retrieve(<code>first</code>) and previous page's end cursor(<code>after</code>).</p>
<p>This way of data retrieval is known as <a target="_blank" href="https://www.yaphc.com/pagination-deceptively-simple-task">pagination</a>, a way to fetch a large amount of data in small batches in order not to overwhelm the server.</p>
<p><strong>Fig 8. simplified version of how pagination works</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654333782475/ceexBB6ZH.png" alt="pagination intro" /></p>
<p><strong>Gotta get 'em all</strong></p>
<p>Now, we know how to construct the request to get media data, we just have to use <code>has_next_page</code> and <code>end_cursor</code> to retrieve the data until we are happy, or until instagram decides to activate the ban hammer. 🙊</p>
<p>Also, it looks like instagram imposes a limit of <strong>50</strong> items for each media page. So that's <strong>483</strong> requests to scrape all of 9gag's media.</p>
<p>If each request takes <strong>1 second</strong> to complete, and we add a random delay of <strong>0.5 - 1.5 seconds</strong> between each request, and ignoring everything else, it will take around <strong>483 * (1 + 1) = 16</strong> <strong>minutes</strong> to scrape all of 9gag's media.</p>
<h2 id="heading-tips-to-scrape-instagram-safely">Tips to scrape instagram safely</h2>
<p>There is always a risk that instagram may issue an IP ban(temporary and permanent) when hitting its server programatically.</p>
<p>However, there are some guidelines to make this venture less risky.</p>
<p><strong>1. Mimic human behaviour</strong></p>
<p>This is the most important tip. No human will make requests in the same exact way every time, e.g. pausing for some time after every request, making <strong>50 requests per second</strong>.</p>
<p>Add some random behaviour in the process. Pause for a random duration between 1-2 seconds after each request</p>
<p>Use common request headers to convince the server that the request comes from a real person using a web browser. Some of them are "<strong>user-agent</strong>", "<strong>accept</strong>", "<strong>accept-encoding"</strong>, "<strong>referer</strong>".</p>
<p>This article provides some useful tips on how to <a target="_blank" href="https://www.scrapehero.com/how-to-prevent-getting-blacklisted-while-scraping/">avoid being blacklisted when scraping</a> websites.</p>
<p><strong>2. Instagram's rate limit</strong></p>
<p>It was reported that the limit of media scraping is around <strong>150-200 requests per 2 minutes</strong>. It is good to keep this in mind and experiment with it.</p>
<p><strong>3. Instagram's soft IP ban</strong></p>
<p>Instagram gets angry when we make a lot of requests in a short period of time, especially as an unauthenticated user.</p>
<p>When that happens, one of these two things need to happen:</p>
<ul>
<li>Wait it out</li>
<li>Figure out a way to make request as an authenticated user(I have not figured it out yet. <a target="_blank" href="https://github.com/hanchiang/instagram-node-api/issues/16">Help wanted</a>?)</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This was a little fun project to pique my own curiosity in finding viral posts on instagram. I hope this post is useful to inspire people to experiment with web development.</p>
<p>Feel free to check out <a target="_blank" href="https://github.com/hanchiang/instagram-node-api/blob/master/src/commands/scrape/README.md">my project</a>!</p>
<h2 id="heading-disclaimer">Disclaimer</h2>
<p>This post is intended to be educate and inform people of the possibility of retrieving instagram data from non-official ways, and is in no way endorsing such actions.</p>
<p>Do it at your own risk.</p>
]]></content:encoded></item><item><title><![CDATA[Reverse geocode cities from geographic coordinates]]></title><description><![CDATA[Reverse geocode is used to convert latitude-longitude coordinates to a list of locations, which can then be used in search results. In many consumer…]]></description><link>https://yaphc.com/reverse-geocode-cities-from-coordinates</link><guid isPermaLink="true">https://yaphc.com/reverse-geocode-cities-from-coordinates</guid><category><![CDATA[reverse geocode]]></category><category><![CDATA[map search]]></category><category><![CDATA[work]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Thu, 30 Jul 2020 09:30:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654334072795/5HRJaC0mZ.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Reverse geocode is used to convert latitude-longitude coordinates to a list of locations, which can then be used in search results.</p>
<p>In many consumer applications, the search experience is one of the most important aspects of consumer satisfaction. Search usually comes in these forms:</p>
<ul>
<li>Pre-defined search tags(e.g. cuisine, location)</li>
<li>Free-text fields</li>
<li>Map</li>
</ul>
<p>Also, there are a wide variety of filters to refine the results.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>In this post, I will be sharing the approach I used to implement the feature to <strong>reverse geocode</strong> in <strong>map</strong> search and match it against a <strong>pre-defined list of locations</strong>.
This is one of the more interesting features that I did as part of my work.</p>
<p>For this example, let's use <strong>New Zealand</strong> as the place of interest, with its <strong>cities</strong> as the search locations.</p>
<p>There was nothing out of the ordinary when I was working on this feature. All I need are the list of pre-defined locations, input coordinates, and a way to check whether a point is inside a polygon.</p>
<p>Within a short period of time, this feature was developed, tested, and pushed to production.</p>
<p>After a few days, I decided to play around with the feature on the mobile application, trying out various zoom levels to make sure that the app is able to receive the expected locations.</p>
<p>Unfortunately, no locations were returned when the map is zoomed out far enough to show the entire <strong>New Zealand</strong> area. But, when the map is zoomed in a little, the reverse geocode feature returns the expected locations.</p>
<p>I was confused, and don't know why this happened. But I guess it must be because of the boundary of the map.</p>
<p>So, I looked up the <a target="_blank" href="https://journeynorth.org/tm/LongitudeIntro.html">longitude and latitude markings on the world map</a> and indeed, <strong>New Zealand</strong> is right next to the longitude boundary, where the longitude becomes negative as it crosses over to the Americas.</p>
<p>To confirm, I logged out the coordinates of the northeast and southwest bounding box, which showed that the longitude of the northeast point is negative and the longitude of the southwest point is positive. This confirmed my hypothesis.</p>
<p><strong>New Zealand and the longitude boundary on its right, where it becomes negative</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654334299880/EMgxRayUo.png" alt="NZ and other side of the world" /></p>
<p>Therefore, there are three edge cases to take care of:</p>
<ol>
<li>When longitude crosses over</li>
<li>When latitude crosses over</li>
<li>When longitude and latitude crosses over</li>
</ol>
<h2 id="heading-preparation">Preparation</h2>
<p>Here are the data that we need to prepare beforehand:</p>
<ul>
<li>A list of pre-defined locations that we want to support(Can be from a database, internal service, etc)</li>
<li>Polygon points(list of latitude-longitude pairs) for every location</li>
</ul>
<p><strong>Fig 1. For Auckland, I mark out the polygon sides and take note of the latitude-longitude pairs.</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654334373533/YdLfjc4AO.png" alt="map of auckland" /></p>
<p>Fig 2. Zoomed in version of Fig 1
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654334447472/8AB1n-T_s.png" alt="map of auckland zoomed in" /></p>
<p>We will also use <a target="_blank" href="http://download.geonames.org/export/dump/">GeoNames</a>, a geographical database that provides useful information about a location such as <code>asciiName</code>, <code>latitude</code>, <code>longitude</code>. This data will be used for a <strong>k nearest neighbour</strong> search as a backup in case there are no results matching any of the polygon points above.</p>
<h2 id="heading-solution-overview">Solution overview</h2>
<p>Here are the steps for the querying the locations, stopping at the <strong>first</strong> step with matching results:</p>
<ol>
<li>Look for cities within the bounding box(southeast and northwest lat-long pairs). Used for the case when the map is <strong>zoomed out</strong>. (See Fig 1)</li>
<li>Look for bounding box within cities. Used for the case when the map is zoomed in. (See Fig 2)</li>
<li>(<strong>Backup</strong>) Look for the nearest locations from the bounding box using <strong>GeoNames</strong> data</li>
</ol>
<h2 id="heading-the-main-logic">The main logic</h2>
<h3 id="heading-pre-process-geonames-data">Pre-process GeoNames data</h3>
<p>First, we need to write code to download <a target="_blank" href="http://download.geonames.org/export/dump/">GeoNames</a> data and process them into a <a target="_blank" href="https://en.wikipedia.org/wiki/K-d_tree">k-dimensional tree</a> using the <a target="_blank" href="https://github.com/luk-/node-kdt">kdt</a> package.</p>
<p>With the <strong>kdt</strong> package, creating a <strong>k-d tree</strong> is as simple as this:</p>
<p><code>kdt.createKdTree(data, distanceFunction, ['latitude', 'longitude']);</code></p>
<p>The first parameter is the <strong>GeoNames</strong> data, the second parameter is the function used to calculate the <a target="_blank" href="http://www.movable-type.co.uk/scripts/latlong.html">distance between two points on a sphere</a>, and the last parameter is an array of the latitude and longitude field names</p>
<h3 id="heading-1-look-for-cities-in-the-bounding-box">1. Look for cities in the bounding box</h3>
<p>The first step in the query process is to search for locations inside the given bounding box. Since the rectangle bounding box will be the polygon in which every city will be tested against, a simple range check is needed.</p>
<p>Referring to Fig 1 above, all the relevant cities will be captured if the entire map is taken as the bounding box.</p>
<p>The pseudocode looks something like this:</p>
<pre><code><span class="hljs-keyword">For</span> <span class="hljs-keyword">each</span> city <span class="hljs-keyword">in</span> <span class="hljs-type">polygon</span> list
    <span class="hljs-keyword">For</span> <span class="hljs-keyword">each</span> <span class="hljs-type">point</span> <span class="hljs-keyword">in</span> the city
        <span class="hljs-keyword">Check</span> whether bounding <span class="hljs-type">box</span> contains <span class="hljs-type">point</span>
        <span class="hljs-keyword">If</span> yes, match city <span class="hljs-keyword">to</span> the pre-defined <span class="hljs-keyword">location</span> list <span class="hljs-keyword">and</span> break <span class="hljs-keyword">out</span> <span class="hljs-keyword">of</span> the <span class="hljs-keyword">loop</span>
<span class="hljs-keyword">Return</span> matched locations
</code></pre><p><strong>Function to check whether the bounding box contains a point</strong></p>
<p>Next, the function to check whether the bounding box contains a point is the key to handle the 3 edge cases of the longitude-latitude crossing over as mentioned above.</p>
<p>Referring to the <a target="_blank" href="https://journeynorth.org/tm/LongitudeIntro.html">longitude-latitude map</a>, we can see that longitude(x-axis) can take values from <strong>-180 to 180</strong>, and latitude(y-axis) from <strong>-90 to 90</strong>.</p>
<p>These are the conditions that must be fulfilled for the <strong>usual</strong> case of longitude increasing over the x-axis, and latitude increasing over the y-axis:</p>
<ul>
<li>Latitude: <code>southwest latitude &lt;= point latitude &lt;= northeast latitude</code></li>
<li>Longitude: <code>southwest longitude &lt;= point longitude &lt;= northeast longitude</code></li>
</ul>
<p>Similarly, these are the conditions for the case of longitude-latitude <strong>cross over</strong>, which need a little imagination to be able to visualise the process:</p>
<ul>
<li>Latitude: <code>-90 &lt;= point latitude &lt;= northeast latitude</code> <strong>OR</strong> <code>southwest latitude &lt;= point latitude &lt;= 90</code></li>
<li>Longitude: <code>-180 &lt;= point longitude &lt;= northeast longitude</code> <strong>OR</strong> <code>southwest longitude &lt;= point longitude &lt;= 180</code></li>
</ul>
<p>Here's the javascript code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { boundingBox, point } = request;
<span class="hljs-keyword">const</span> { latitude, longitude } = point;
<span class="hljs-keyword">const</span> { northEast, southWest } = boundingBox;

<span class="hljs-keyword">let</span> isWrapAroundLat = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">let</span> isWrapAroundLon = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">let</span> isLonWithinNegativeWrappedRegion = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">let</span> isLatWithinNegativeWrappedRegion = <span class="hljs-literal">false</span>;

<span class="hljs-keyword">const</span> isLatWithinUsualRegion = latitude &gt;= southWest.latitude &amp;&amp; latitude &lt;= northEast.latitude;
<span class="hljs-keyword">const</span> isLonWithinUsualRegion =
    longitude &gt;= southWest.longitude &amp;&amp; longitude &lt;= northEast.longitude;

<span class="hljs-keyword">if</span> (northEast.longitude &lt; southWest.longitude) {
  isWrapAroundLon = <span class="hljs-literal">true</span>;
  isLonWithinNegativeWrappedRegion =
    (longitude &gt;= southWest.longitude &amp;&amp; longitude &lt;= <span class="hljs-number">180</span>) ||
    (longitude &gt;= <span class="hljs-number">-180</span> &amp;&amp; longitude &lt;= northEast.longitude);
}
<span class="hljs-keyword">if</span> (northEast.latitude &lt; southWest.latitude) {
  isWrapAroundLat = <span class="hljs-literal">true</span>;
  isLatWithinNegativeWrappedRegion =
    (latitude &gt;= southWest.latitude &amp;&amp; latitude &lt;= <span class="hljs-number">90</span>) ||
    (latitude &gt;= <span class="hljs-number">-90</span> &amp;&amp; latitude &lt;= northEast.latitude);
}
<span class="hljs-keyword">if</span> (isWrapAroundLat &amp;&amp; isWrapAroundLon) {
  <span class="hljs-keyword">return</span> isLonWithinNegativeWrappedRegion &amp;&amp; isLatWithinNegativeWrappedRegion;
}
<span class="hljs-keyword">if</span> (isWrapAroundLat) {
  <span class="hljs-keyword">return</span> isLatWithinNegativeWrappedRegion &amp;&amp; isLonWithinUsualRegion;
}
<span class="hljs-keyword">if</span> (isWrapAroundLon) {
  <span class="hljs-keyword">return</span> isLonWithinNegativeWrappedRegion &amp;&amp; isLatWithinUsualRegion;
}
<span class="hljs-keyword">return</span> isLatWithinUsualRegion &amp;&amp; isLonWithinUsualRegion;
</code></pre>
<p>With this, the main work required to fix the issue of no matching results when the latitude-longitude of the bounding box crosses over is completed.</p>
<h3 id="heading-2-look-for-bounding-box-in-cities">2. Look for bounding box in cities</h3>
<p>Here, we are looking for bounding box inside the cities.</p>
<p>Referring to Fig 2, Auckland should still show up in the result list even though only a small part of it is visible.</p>
<p>Here steps for this part:</p>
<pre><code>Interpolate perimeters <span class="hljs-keyword">of</span> the bounding <span class="hljs-type">box</span>
<span class="hljs-keyword">For</span> <span class="hljs-keyword">each</span> <span class="hljs-type">point</span> <span class="hljs-keyword">in</span> bounding <span class="hljs-type">box</span> perimeter
    <span class="hljs-keyword">For</span> <span class="hljs-keyword">each</span> city <span class="hljs-keyword">in</span> the <span class="hljs-type">polygon</span> list
        <span class="hljs-keyword">Check</span> whether the <span class="hljs-type">point</span> <span class="hljs-keyword">is</span> inside the city
        <span class="hljs-keyword">If</span> yes, match city <span class="hljs-keyword">to</span> the pre-defined <span class="hljs-keyword">location</span> list <span class="hljs-keyword">and</span> break <span class="hljs-keyword">out</span> <span class="hljs-keyword">of</span> the <span class="hljs-keyword">loop</span>
<span class="hljs-keyword">Return</span> matched locations
</code></pre><p><strong>Fig 3. Blue dots are the bounding box inputs, red dots are the other 2 points of the box inferred from the bounding box input. Black dots are the interpolated perimeter points.</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654334758394/vZafHtfA6.png" alt="auckland zoomed in with bounding box perimeter" /></p>
<p><strong>Function to check whether a city contains a point</strong></p>
<p>This is done through the <a target="_blank" href="https://github.com/mikolalysenko/robust-point-in-polygon">robust-point-in-polygon</a> package.</p>
<h3 id="heading-3-look-for-nearest-locations-from-the-bounding-box-using-geonames-data">3. Look for nearest locations from the bounding box using GeoNames data</h3>
<p>This third step is used as a fallback in the unlikely event that the previous two steps did not return any result.</p>
<p>Following the <a class="post-section-overview" href="#pre-process-geonames-data">pre-processing step of the GeoNames data</a> where the <strong>k-d tree</strong> was created, it is time to get the nearest neighbours of each corner of the bounding box:</p>
<p><code>kdTree.nearest(point, 10);</code></p>
<p>The code above retrieves the 10 nearest locations from one of the bounding box corners. After that, like before, match it to the pre-defined list of locations and return the matching results.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>With a working data set of 10 polygons with an average of 12 points per polygon, there is no adverse impact on performance.</p>
<p>If the map is zoomed in, most/all of the results will be retrieved from step 1(find cities in bounding box).</p>
<p>If the map is zoomed out, most/all of the results will be retrieved from step 2(find bounding in cities).</p>
<p>If the above fails, <a target="_blank" href="http://download.geonames.org/export/dump/">GeoNames</a> will hopefully come to our rescue.</p>
]]></content:encoded></item><item><title><![CDATA[Challenges in designing a great user onboarding experience]]></title><description><![CDATA[Designing a great onboarding, sign in experience is not easy because everyone is different and behaves differently. However, doing it well can put a smile…]]></description><link>https://yaphc.com/challenges-in-designing-user-onboarding-experience</link><guid isPermaLink="true">https://yaphc.com/challenges-in-designing-user-onboarding-experience</guid><category><![CDATA[user onboarding]]></category><category><![CDATA[user experience]]></category><category><![CDATA[work]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 31 May 2020 12:10:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654335168671/5Lg-emV9z.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Designing a great onboarding, sign in experience is not easy because everyone is different and behaves differently. However, doing it well can put a smile on users' faces.
For most B2C applications, onboarding should be quick, intuitive, and easy to navigate. The key is to offer a high-value, frictionless experience with minimal effort.</p>
<p>I came across an article that describes <a target="_blank" href="https://uxplanet.org/most-common-log-in-problems-and-solutions-163a6209c0eb">common problems with login and its solutions</a>, and another that talks about the <a target="_blank" href="https://uxdesign.cc/15-rules-of-user-sign-in-experience-ae9011d04ee3">rules for sign in experience</a>. Both contain useful information to consider when designing the entire onboarding and sign-in flow.</p>
<p>Authentication and identity is one of the first few features I worked on. At its basic level, it allows users to register an account, sign in, link accounts, and manage their profile information.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654341865128/UbLxMBd7b.png" alt="sign-in-schema.png" /></p>
<p>There are a few areas that I found to be more challenging, which requires a good understanding of the expected user behaviours and experience before designing the solution.</p>
<p>I may have skipped a few steps, which ultimately resulted in these discoveries. 😯</p>
<p>First, let's list down the user requirements:</p>
<ol>
<li>As a user, I want to be able to sign in with different methods according to my preferences and specific needs</li>
<li>As a user, I want to be able to set a password on my account for security purposes</li>
<li>As a user, I want the system to provide helpful advice to rectify errors when I am unable to sign in</li>
</ol>
<h2 id="heading-multiple-sign-in-methods">Multiple sign in methods</h2>
<p>Allowing users to sign in with different ways is a very common pattern in consumer applications. This is useful because it provides <strong>flexibility</strong> to how they want to sign in to the service.</p>
<p>Some people do not like to type in email and password just to register an account, while other more <strong>privacy-conscious</strong> users do not want their social account's information to be accessed.</p>
<p>However, with flexibility comes complexity as there are more paths a user can take to achieve a goal, sometimes causing conflicts.</p>
<h2 id="heading-email-is-taken-same-or-different-user">Email is taken: Same or different user?</h2>
<p>Suppose a user signs up with <a target="_blank" href="mailto:e@e.com">e@e.com</a>, then later another user(could be the same person as before) signs up with Google using the same email <a target="_blank" href="mailto:e@e.com">e@e.com</a>.</p>
<p>A question comes to mind:</p>
<blockquote>
<p>Should the system recognise this as 2 different users and therefore create a new user account or 1 user with two sign-in methods?</p>
</blockquote>
<p><strong>Useful error message</strong></p>
<p>My team decided to reject the Google sign-up using an email that exists in the system, and show a <strong>helpful message</strong> that tells the user to sign in with email. The reason is to prevent the same person from accidentally creating multiple accounts when their actual intention might be to sign in with a method that they thought they have previously linked.</p>
<p><strong>What about email impersonation?</strong></p>
<p>If a random person were to register an account with my email, I will be unable to register an account using my own email, and that is not cool.</p>
<p>Also, different social account providers have their own rules regarding email verification. Facebook requires email verification, while google does not. So, it is safe to assume that a user signing up with Facebook is the rightful owner of that email, but the same can't be said for Google.</p>
<p>This is something that an <strong>email verification</strong> flow takes care of easily. A new user account requires verification in order to perform the main business functions, and every business serious about their work will have a form of verification.</p>
<p>On top of that, we have an email uniqueness constraint that requires the email of new signups to be <strong>unique across all sign-in methods</strong>. This adds another layer of safeguard to deter rogue users.</p>
<h2 id="heading-account-linking">Account linking</h2>
<p>Referring back to the issue of differentiating whether 2 sign-ups using the same email should be considered as a separate account or the same account with 2 sign-in methods, we decided <strong>not to do automatic account linking</strong> because the users' expectation is to link the account in their profile themselves.</p>
<blockquote>
<p>We believe that an explicit over implicit approach presents a more intuitive experience.</p>
</blockquote>
<h2 id="heading-email-usage-and-modification">Email usage and modification</h2>
<p>Using the same email for authenticating and marketing communications purposes <strong>simplifies</strong> usage from a user's perspective and maintenance from a development perspective.</p>
<p>If a user changes their sign-in email, they should subsequently receive all communications through that same email.</p>
<p>Another option is to use a <strong>secondary</strong> email as a communication channel. The benefit is the <strong>separation of authentication and communication</strong>. However, I am not convinced that the benefits outweigh the complexity of managing two emails.</p>
<h2 id="heading-user-signed-out-and-forgot-the-sign-in-methods">User signed out and forgot the sign-in method(s)</h2>
<p>It is possible that some time down the road a user may be signed out of the service for some reasons:</p>
<ul>
<li>Computer broke down and needed a complete re-installation of the operating system</li>
<li>Signed out of the service, intentionally or unintentionally.</li>
<li>The user is a power user and decides to clear browser storage</li>
</ul>
<p>For services that only allow a single sign-in method, this is not an issue at all. For services that offer multiple sign-in methods, a user may need to go through multiple unsuccessful sign-in attempts before succeeding or giving up.</p>
<p>Although such situations may be rare, it still brings up an important and relevant user pain point</p>
<p>Everyone uses multiple services. Personally, I sign in to various applications with different methods. I cannot and don't want to remember the exact combinations for each one.</p>
<p>From my point of view, for services dealing with non-confidential information, I should stay signed in as long as possible. In the event that I am signed out for any reason, it should be easy for me to get back in again.</p>
<blockquote>
<p><em>Services should be designed to</em> <a target="_blank" href="https://uxdesign.cc/human-error-an-important-ingredient-in-great-designs-5cd1c278ba7f">forgive user mistakes</a> <em>and offer a way to recover</em></p>
</blockquote>
<h2 id="heading-be-more-user-centric">Be more user-centric</h2>
<p><strong>(Development) hats off</strong></p>
<p>Developers have the tendency to jump right into the action and develop cool features that no one really wants to use. I am guilty of that. 😅</p>
<p>Take off the developer hat for a moment and put yourself in a user's shoe, better yet see things from multiple user personas' perspectives to understand the pain points of different user segments and profiles.</p>
<p><strong>Read, discuss, iterate</strong></p>
<p>Great products emerge after multiple rounds of debate and improvements.</p>
<p>Having knowledge in topics such as human-computer interaction, visual design, behavioural sciences like psychology, anthropology, and cognitive science is invaluable in designing great products.</p>
<p>Some of my favourite sources of User Experience readings are <a target="_blank" href="https://uxplanet.org/">UX planet</a>, <a target="_blank" href="https://uxdesign.cc/">UX collective</a>, <a target="_blank" href="https://www.interaction-design.org/">Interaction Design Foundation</a></p>
<p><strong>Look at what others do</strong></p>
<p>Chances are, the problems we are trying to solve have been solved by great organisations with talented product and engineering teams.</p>
<p>Here are some examples:</p>
<p><strong>Klook: Signed up with social account, prompt to link email</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654344086107/rf6YoJQ95.png" alt="klook add email address to link to account" /></p>
<p><strong>Pinterest: Link an account</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654344134948/GD8BY9GdH.png" alt="pinterest add another account" /></p>
<p><strong>Airbnb: Sign up with social account, prompt to set a password</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654344175129/POx7SnQ6Z.png" alt="airbnb social sign up set password" />    </p>
<p>Quora: Sign up with social account, set password
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654344219000/HAQKxDO5R.png" alt="quora social sign up set password" /></p>
<p><strong>Quora: Option to add another email</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654344300696/wYhBE4e9v.png" alt="quora profile add another email" /></p>
<p><strong>Topbuzz: Link email account</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654344388026/AF0r2MxbR.png" alt="top buzz connect email" />    </p>
<p>From sampling the onboarding experience of Airbnb, Quora, Klook, Pinterest, Topbuzz, it seems like allowing users to set a password, and optionally adding a new sign-in email, is a common approach.</p>
<h2 id="heading-summary">Summary</h2>
<p>Creating great products that people enjoy using is difficult.</p>
<p>I vaguely remembered a phrase that the professor from my human-computer interaction course said:</p>
<blockquote>
<p>Remember, <a target="_blank" href="https://uxplanet.org/are-users-really-stupid-92de6901e2be">users are dumb</a>, so are designers</p>
</blockquote>
<p>I could almost hear the gasp from everyone. But shortly after, we understood what the professor meant.</p>
<p>Users are "dumb" because everyone is different, and behaves differently. They know the problems that they are facing but not the solutions.</p>
<p>Designers are "dumb" because they <strong>assume</strong> they understand their users and know how to solve their problems. Designers who take a narrow perspective in their work and refuse to take feedback, tend to design products that do not solve users' problems, and may even worsen them.</p>
<p>By the same token, developers are "dumber" because in a typical team structure developers are the furthest away from the end-users, and have the least understanding of users' problems.</p>
<blockquote>
<p>Ultimately, creating a great product is not easy. It requires alignment of <strong>intentions</strong> and <strong>assumptions</strong>. No one gets it right the first time.</p>
</blockquote>
<p>Finally saving the best for last, I recently discovered <a target="_blank" href="https://growth.design/">Growth.Design</a>, a website that teaches people how to build products that your users will love through design principles and psychology, as well as in-depth case studies of popular companies.</p>
<p>I believe anyone who is interested in building great products will benefit from using the website.</p>
]]></content:encoded></item><item><title><![CDATA[API versioning: The inevitable breaking change in software]]></title><description><![CDATA[RESTful APIs are interfaces for computers to communicate with one another, and are ideally set in stone. However, even with great design knowledge and…]]></description><link>https://yaphc.com/api-versioning-inevitable-breaking-change-in-software</link><guid isPermaLink="true">https://yaphc.com/api-versioning-inevitable-breaking-change-in-software</guid><category><![CDATA[api versioning]]></category><category><![CDATA[breaking changes]]></category><category><![CDATA[work]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Mon, 25 May 2020 12:28:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654345439811/E_DJayXqQ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>RESTful APIs are interfaces for computers to communicate with one another, and are ideally set in stone. </p>
<p>However, even with great design knowledge and practices, demands and requirements of systems evolve over time, which may cause incompatibility with older versions. The use of API versioning helps to manage these incompatibilities, which are also called <strong>breaking changes</strong>.</p>
<p>API versioning is a concept that I have heard of some time ago but did not realise its significance until I needed to implement them. It is also one of the concepts that are rather subjective in nature, with no single superior approach to rule them all.</p>
<h2 id="heading-overview">Overview</h2>
<p><strong>When is versioning required?</strong></p>
<blockquote>
<p>Change in an API is inevitable as your knowledge and experience of a system improves. Managing the impact of this change can be quite a challenge when it threatens to break existing client integrations.</p>
</blockquote>
<p>It is needed when the application logic changes, which results in a <strong>different response format</strong>, such as in my case of <a target="_blank" href="https://www.yaphc.com/pagination-deceptively-simple-task">implementing pagination</a>.</p>
<p>It is also important to mention that breaking changes are most likely to happen when building APIs that serve a <strong>mobile</strong> application. This is because each build submission of the mobile application captures the snapshot of the application code at that time, therefore it is <strong>unable to adapt</strong> to changes to the APIs from that point onward. This reinforces the importance of understanding the requirements and in order to design a robust solution.</p>
<p>In my current role, certain parts of the system that were designed at the initial phase were done without a full understanding of the business domain and its implications, which is normal in startup environments.</p>
<p>As a result, some APIs were awkward to work with because of reasons like confusing naming conventions, business requirements are not fully met, etc.</p>
<h2 id="heading-versioning-approaches">Versioning approaches</h2>
<p>There are a few common ways to implement the versioning, which have been discussed in great depth such as the one from <a target="_blank" href="https://www.troyhunt.com/your-api-versioning-is-wrong-which-is/">Troy Hunt</a>, <a target="_blank" href="https://www.mnot.net/blog/2012/12/04/api-evolution">Mark Nottingham</a>:</p>
<ul>
<li>URL path: e.g. <em>api.example.com/v2/</em></li>
<li>Query parameters: e.g. <em>api.example.com?version=2</em></li>
<li>Header: e.g. <em>api-version: v2</em></li>
</ul>
<h3 id="heading-1-url-path">1. URL path</h3>
<p>The simplest of all is to embed the major version in the URL to use the appropriate version of a resource.</p>
<p>Under this design, the version applies to the entire service. If a certain API requires a breaking change, the frontend clients need to adjust the version for <strong>that particular service</strong>.</p>
<p>Deprecating an API would involve keeping the routes live, updating the logic to return an appropriate response.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Failures are <strong>detected early</strong> at the API gateway level. Using a URL that does not correspond to a resource will result in an error response without passing the request to backend services.</li>
<li>A specific version of a resource means that there is no need for additional logic to determine the <strong>correct code execution path</strong> in the backend services, safeguarding against an outage due to incorrect code routing.</li>
<li>No need to store a list of APIs in the database and write custom code to validate</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>A quick and cheap solution that can become messy if it is not maintained properly</li>
<li>Require an additional set of entries in API gateway</li>
<li>There is a potential for code duplication at the service level if the logic for different versions are not managed properly</li>
</ul>
<h2 id="heading-2-header">2. Header</h2>
<p>This involves adding a custom HTTP request header to indicate the resource version.</p>
<p>Here, the same version is used for all services. This means that if a service contains an API that needs a version update, frontend client will update a single version that will be used for requests to <strong>all services</strong>.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Does not require an additional list of entries in API gateway</li>
<li>There is no service-level code duplication</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>Extra care needs to be taken to ensure that the proper code path is executed for different APIs with different breaking versions, since the condition to check for will be different. Otherwise, it may result in an outage for that API or even a crash in the entire service.</li>
</ul>
<h2 id="heading-implementation-workflow">Implementation workflow</h2>
<p>After some discussion, the decision was to go with the header approach, because it is a more structured method that allows us to maintain <strong>code quality</strong> and implement a centralised logic to handle the versions. The tradeoff is that the documentation of various APIs versions needs to be very detailed, and the logic to determine which version of the code to execute needs to be done carefully.</p>
<p><strong>Implementation overview</strong></p>
<p>Each HTTP request will receive an <em>api-version</em> entry in the header. Following that are several processing steps:</p>
<ol>
<li>Validate the <em>api-version</em> input. An empty input is allowed.</li>
<li>If the list of API versions is not saved in memory, retrieve the latest copy.</li>
<li>If the input is not specified, set the initial API version in the header. Otherwise, check that the input is found in the list of valid versions before setting it in the header. An invalid version will be responded with an error.</li>
</ol>
<p><strong>Usage in services</strong></p>
<p>Using it in the services is a matter of a few simple but crucial lines of if-else code that triggers the appropriate code according to the version.</p>
<p>To illustrate the importance of the conditional versioning logic, let's say version 1 of a search hotels API expects to receive the following query string: <em>name</em>, <em>pricePointMin</em>, <em>pricePointMax</em></p>
<p><code>api.example.com/search?name=lhotel&amp;pricePointMin=2&amp;pricePointMax=5</code></p>
<p>While version 2 requires the following query string: <em>name</em>, <em>pricePoints</em></p>
<p><code>api.example.com/search?name=1hotel&amp;pricePoints=2,4,5</code></p>
<p>In the case of executing code for version 2 using version 1's request parameters and vice versa, the best outcome is an error response to clients which is not too damaging, the worst would be a crash of the entire service.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Business needs and requirements <strong>evolve over time</strong>, and the software will follow suit. For this particular topic, my personal opinion is that the URL approach is a quick way to get things done, and the header approach is suitable for meeting the needs of organisation that is scaling or has achieved scale.</p>
<p>Regardless of the approach, it is important to have clear documentation to align expectations among team members, as well as a strategy for deprecating older APIs so that clients using older versions won't be left with a broken application.</p>
]]></content:encoded></item><item><title><![CDATA[Pagination: The deceptively simple task]]></title><description><![CDATA[Pagination is the process of separating data into multiple discrete pages. In the context of web and mobile applications, this can either be in the form on…]]></description><link>https://yaphc.com/pagination-deceptively-simple-task</link><guid isPermaLink="true">https://yaphc.com/pagination-deceptively-simple-task</guid><category><![CDATA[elasticsearch]]></category><category><![CDATA[Redis]]></category><category><![CDATA[Pagination]]></category><category><![CDATA[infinite scrolling]]></category><category><![CDATA[work]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 17 May 2020 12:48:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654345973968/MzX7MVSA7.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Pagination is the process of <strong>separating data</strong> into multiple discrete pages. In the context of web and mobile applications, this can either be in the form on <strong>numbered pages</strong> as seen in google search results or <strong>infinite scrolling</strong> in social media feed. The decision process behind choosing either approach is not the objective of this post, but rather it is about the implementation of the backend data flow.</p>
<p>This is the first moderately technical post on this website, and I am happy to finally start writing a topic that is more related to the art of software engineering.</p>
<p><strong>Why is pagination needed?</strong></p>
<p>If a certain product feature does not yield benefit to end users, then it is worthless.</p>
<p>Pagination has been proven to improve user experience in a <a target="_blank" href="https://netpeaksoftware.com/blog/pagination-and-seo-why-do-you-need-it-and-how-to-avoid-common-mistakes">few ways</a>:</p>
<ol>
<li><p>Loading a small chunk of data each time reduces the data bandwidth usage, which ultimately improves page loading speed and Search Engine Optimisation(SEO). The benefit of downloading lesser data is more pronounced in places with poor network connectivity.</p>
</li>
<li><p>Splitting content into multiple pages helps to retain readers' attention, increasing the likelihood that they will enjoy their reads. Imagine how poor of a reading experience it will be if the home page of this website displays over 100 posts with its full content.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654346046274/HoJhKjiz9.png" alt="google search results pages" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654346083983/OPwJLhAE1.png" alt="infinite scrolling on mobile" /></p>
<h2 id="heading-overview">Overview</h2>
<p>A few months into my job, I was learning and using cool technologies such as <a target="_blank" href="https://www.elastic.co/">Elasticsearch</a>, <a target="_blank" href="https://redis.io/">Redis</a>. Elasticsearch is used for implementing a basic search feature, and Redis is used for optimising another aspect of search that is not related to the former.</p>
<p>Elasticsearch is a common tool used for products that want a comprehensive search experience for their end-users. It is a powerful full-text search engine that comes with great out-of-box features such as autocomplete, phrase suggestion, flexible analyser, tokeniser, query language.</p>
<p>I used Elasticsearch to implement the <strong>backend</strong> for the infinite scrolling experience on the mobile and web app. My preparation for this task included reading up what pagination is all about, several common implementations.</p>
<p>What I thought was a simple coding task turned out to be not so simple after all, when my team and I discovered inconsistencies and irregularities in the search result after a few months.</p>
<p>In short, the tragedy was due to an oversight in the overall <strong>data flow</strong> - the implementations that I have read up on have all their data processing requirements in a <strong>single place</strong>, whereas for my case the main data is in one place, and the secondary data is in another.</p>
<p>There are also other potential pagination issues to take note:</p>
<ul>
<li><p>Data freshness. When data in the data store changed, should they be reflected in the current search session?</p>
</li>
<li><p>Bi-directional search. This is used in advanced cases of infinite scrolling where data a few pages outside of the current viewport are discarded to conserve memory, which also ties in with the data freshness issues</p>
</li>
</ul>
<p>Indeed, pagination is one domain of software engineering which has been greatly <a target="_blank" href="https://hackernoon.com/guys-were-doing-pagination-wrong-f6c18a91b232">researched</a>, experimented, and <a target="_blank" href="https://developers.facebook.com/docs/graph-api/using-graph-api/#paging">implemented</a>, yet there are still bad ones lying around.</p>
<h2 id="heading-pagination-v10-3-simple-steps">Pagination v1.0: 3 simple steps</h2>
<p>Here are the general steps taken to produce search results for any user query:</p>
<ol>
<li><p>Query elasticsearch</p>
</li>
<li><p>Search for availability from another backend service</p>
</li>
<li><p>Return data that contain availability to user</p>
</li>
</ol>
<p>The initial implementation is really straightforward. All I need to do is to use the <code>from</code> parameter from Elasticsearch as the offset - the number of documents to skip over. Next, call an availability API, and finally filter the search results that contain availability and return the end result.</p>
<h3 id="heading-the-problem">The problem</h3>
<p>The major mistake in this implementation is that the offset passed to Elasticsearch does not account for the availability.</p>
<p><strong>Wrong offset used for pagination</strong></p>
<p>For example, a client sends a request for 30 items, Elasticsearch is queried and returns 30 results, but there is no guarantee that all 30 of them have availability, so let's say that after filtering availability we have <strong>22</strong> results. On the next request, the client sends requests for another 30 items and sends in <strong>offset 22</strong> to skip the 22 items that are in the result set. This is a problem because Elasticsearch will return the 23rd item onwards, from which the 23rd to 30th item have already been searched and returned in the first request, resulting in <strong>duplication</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654346140392/OBBuBGiTm.png" alt="Elasticsearch pagination 1.0" /></p>
<p>This fundamental logic error took some time to figure out, which led to a quickfix.</p>
<h2 id="heading-pagination-v11-the-quick-fix">Pagination v1.1: The quick fix</h2>
<p>After identifying the cause of the duplication problem, a fast rescue in en route. Instead of using the length of the result set returned(i.e. 22) as the offset, the length of the items searched so far is used as the offset(i.e. 30).</p>
<p>Problem solved! Well, not quite...</p>
<h3 id="heading-another-problem">Another problem</h3>
<p>The next problem encountered was that the search will tend to be terminated prematurely if the items with availability are further down the result set, which meant that those items will never appear on the search result page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654346207363/N3kvjRqnB.png" alt="Elasticsearch pagination 1.1" /></p>
<p>This is both damaging and non-damaging. From the perspective of the end-users, they may not suspect anything amiss because there are no strange happenings in the mobile and web application. From the perspective of the business, many items became undiscoverable, causing potential financial losses.</p>
<p>After 2 tries, it became clear that a two-step page-by-page fetch won't work no matter what. After doing more research, a more robust plan was born.</p>
<h2 id="heading-pagination-v20-correctness-first">Pagination v2.0: Correctness first</h2>
<h3 id="heading-overview-1">Overview</h3>
<p>The main idea is to do a bulk fetch of data on the first request, filter for availability, and save the result ids in a <strong>Redis</strong> set, which are used for serving results to users for every page request. A <a target="_blank" href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> is used as the key to the result set, which functions as the <strong>search session key</strong>.</p>
<p>Essentially, for each query, a snapshot of the result set is computed and used to serve for subsequent pages.</p>
<p>For this implementation, the Redis sorted set data structure was chosen because it provides flexible and powerful ways to manipulate the data with <a target="_blank" href="https://redis.io/commands/zrange">zrange</a>, <a target="_blank" href="https://redis.io/commands/zrangebylex">zrangebylex</a>.</p>
<p>The response payload looks something like this:</p>
<pre><code class="lang-plaintext">{
  "payload": {
    "total": 250,
    "hasNext": true,
    "sessionToken": "1d65df36-0072-4fe6-b396-9c851097a9e0",
    "data": []
  }
}
</code></pre>
<h3 id="heading-first-page-request">First page request</h3>
<ol>
<li><strong>Bulk fetch</strong></li>
</ol>
<p>The page size is set to 1000, which is not a high number. But given the data set we had at the time of implementation, it was more than enough.</p>
<ol start="2">
<li><strong>Check availability flags</strong></li>
</ol>
<p>This is a pre-processing step handled by a background job that periodically checks and saves a boolean flag for all merchants and timeslots combination in Redis.</p>
<ol start="3">
<li><strong>Save resulting id list</strong></li>
</ol>
<p>Save the resulting list of id with availability in Redis, with a default expiry of 30 minutes. The reason for saving id rather than the full data object is to reduce memory usage and data inconsistency.</p>
<ol start="4">
<li><strong>Get the full object data</strong></li>
</ol>
<p>With the list of ids, retrieve the full object data from Elasticsearch.</p>
<ol start="5">
<li><strong>Search for availability</strong></li>
</ol>
<p>Search for availability for the first 30 items and return the final result.</p>
<h3 id="heading-subsequent-page-fetch">Subsequent page fetch</h3>
<ol>
<li><strong>Retrieve the list of ids</strong></li>
</ol>
<p>Use the <strong>search session key</strong> to retrieve the list of id using from Redis</p>
<ol start="2">
<li><strong>Get full object data</strong></li>
</ol>
<p>With the list of id, get the full object data from Elasticsearch.</p>
<ol start="3">
<li><strong>Search for availability</strong></li>
</ol>
<p>Search for availability for the first 30 items and return the final result.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654346504466/wq49S74oK.png" alt="Elasticsearch pagination 2.0" /></p>
<h3 id="heading-potential-problems">Potential problems</h3>
<p><strong>1.Availability datafreshness from background job</strong></p>
<p>The background job will take more time to complete as more data fills up Elasticsearch, resulting in a larger window of time that is out of sync with the actual availability. One possible solution is to spin up multiple worker threads to share the workload - 600 loop iterations are run for one single record.</p>
<p><strong>2. Updates to Elasticsearch are not visible</strong></p>
<p>Since the approach takes a snapshot of the result set that matched the query during the first request, updates to the data store will not be visible to the current search session.</p>
<p>For this case, this is a compromise that my team is willing to take to avoid another complicated task of combining and deduplicating the search results from old and new snapshot data.</p>
<p><strong>3. What happens after the bulk fetched data is consumed?</strong></p>
<p>In the example, 1000 items are fetched from Elasticsearch, filtered for availability and saved in Redis. If an incredible user manages to scroll through all 1000 items in the result page, and there are more data in Elasticsearch, another round of bulk fetch and availability filtering needs to take place.</p>
<p>But this works against point 2 above - the new bulk fetch is a <strong>newer snapshot</strong> of Elasticsearch, which is different from the snapshot of the initial bulk fetch.</p>
<p>One possible solution would be to have yet another background job to do subsequent bulk fetches(1001st to 2000th item, 2001 to 3000th item and so forth). The bulk fetch for the first page should be kept to a reasonable size in order for the request to complete fast enough.</p>
<p>Another way of handling this is to take the easy way to ignore any data after the initial bulk fetch data is consumed because it is highly unlikely that users will scroll through thousands of items to decide on a transaction. This may or may not be wise from a business point of view, and requires sufficient empirical evidence to back it up.</p>
<p><strong>4. Memory hog by some users</strong></p>
<p>Rogue or extremely enthusiastic users can trigger many search sessions in a short period of time, potentially causing Redis to run out of memory. This can cause a really poor user experience by evicting old data when they are still actively used.</p>
<p>There are a few measures to keep the probability of this happening low.</p>
<p>First, store only the necessary data in Redis, don't do a wholesale data dump. Next, a rate-limiting mechanism can be used to put a limit on the reasonable number of requests that can be made in a certain amount of time. Also, evict old data out of the data store, configuring the <a target="_blank" href="https://redis.io/topics/lru-cache">eviction policy</a> to suit your own needs.</p>
<h2 id="heading-other-considerations">Other considerations</h2>
<p>Q: Why not store availability in Elasticsearch, then most of the complexity will be gone.</p>
<p>A: I asked this question at the beginning of the solution design phase. The quick win is that search and availability filter will happen at the same place, so there is no need to introduce a cache layer, saving time and money immediately.</p>
<p>However, there are several drawbacks to storing availability, a fast-changing data, in Elasticsearch:</p>
<ol>
<li><p>Every batch of availability data means a bulk update operation to Elasticsearch, which can affect query latency. If the frequency and volume of the availability data are huge enough, this will cause problems with user experience.</p>
</li>
<li><p>Storing an array of availability data as <a target="_blank" href="https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html">nested documents</a> in Elasticsearch results in poor query performance. This is explained in an article by <a target="_blank" href="https://blog.gojekengineering.com/elasticsearch-the-trouble-with-nested-documents-e97b33b46194"><strong>Go Jek</strong></a> where they encountered performance issues with nested documents. They solved the performance issue, but another custom solution that needs to be maintained and has its own inaccuracies.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Pagination in itself is a simple technical concept to understand. However, the devil is in the detail. A proper understanding of the acceptable user experience and tradeoffs is needed in order to design the technical approach. After all, making <a target="_blank" href="https://www.nemil.com/on-software-engineering/think-in-tradeoffs.html">tradeoffs</a> is at the heart of software engineering.</p>
]]></content:encoded></item><item><title><![CDATA[First software engineering role: A year in review]]></title><description><![CDATA[It has been 1 year and 2 months since I started working full time in 2019 Feb 25. Much has happened at work, especially at a small company like mine where…]]></description><link>https://yaphc.com/first-software-engineering-role-review</link><guid isPermaLink="true">https://yaphc.com/first-software-engineering-role-review</guid><category><![CDATA[work]]></category><category><![CDATA[Career]]></category><dc:creator><![CDATA[Yap Han Chiang]]></dc:creator><pubDate>Sun, 26 Apr 2020 13:15:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1654347403639/FaiFSYlUK.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It has been 1 year and 2 months since I started working full time in 2019 Feb 25. Much has happened at work, especially at a small company like mine where situations and decisions can change rapidly.</p>
<p>I thought this would be a good time to take a step back and recount the ups and downs in my first job so far.</p>
<h2 id="heading-good-news">Good news</h2>
<p>Let's start the post on a positive note!</p>
<h3 id="heading-great-mentorship">Great Mentorship</h3>
<blockquote>
<p>When the student is ready the teacher appears</p>
</blockquote>
<p>I can confidently say that mentorship is the greatest gift that I have received in my team. I joined as the first engineer, fourth employee of the company, and started the entire technical system on a blank slate.</p>
<p><strong>The beginning</strong></p>
<p>During the initial phase of my onboarding, I worked closely with my manager, CTO of the company, on various application exercises and discussions and readings on software engineering principles such as <a target="_blank" href="https://martinfowler.com/tags/domain%20driven%20design.html">Domain Driven Design</a>, consistency in distributed systems, data flow in redux, among others.</p>
<p>After going through the exercises, I worked on the initial mobile application prototype demonstrating authentication, identity, and search workflow, together with the corresponding backend services. The regular technical discussions as I learned about data modelling, APIs design on the backend, and component organisation, data logic layer in the frontend.</p>
<p><strong>The growth</strong></p>
<p>As the rest of the engineering team got formed, my manager told me that I was assigned frontend responsibilities, and asked for my preference in areas of responsibility.</p>
<p>I told him that after I enjoyed the work on backend over the past few months and would like to do more backend work moving forward. Shortly after, my request was approved and I continued working on the backend services, while learning from a senior backend engineer, who has 10 years of experience building large-scale systems and leading a team of engineers.</p>
<p>Just to name some of the learnings that I took away from the senior backend engineer:</p>
<ul>
<li>Designing API with backward compatibility</li>
<li>System-wide design considerations such as API versioning</li>
<li>Design of stateful and stateless logic in API services</li>
<li>Importance of idempotent operations in distributed systems, where failures and retries are expected</li>
<li>Importance of identifying race conditions in concurrent operations that manipulate the same data set</li>
<li>Writing and maintaining a reusable library with common functions</li>
<li>Good software engineer practices such as <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/SOLID">SOLID</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Test-driven_development">TDD</a>.</li>
</ul>
<p>My growth continued as we expanded the scope of work to application and database performance testing, design of cron jobs, task queue, search optimisation with redis sorted set.</p>
<p>One important point to note is that growth is not linear, or put in another way, growth does not take place in equal proportions to time.</p>
<p><strong>What I thought growth looks like</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654436062854/BncaBRZ3g.png" alt="skill-time-graph.png" /></p>
<p><strong>What it actually looks like</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654436075531/kRzGfD96K.png" alt="skill-time-graph-non-linear.png" /></p>
<p>Looking back, I am happy and grateful to have the opportunity to learn from a great manager and senior engineer.</p>
<h3 id="heading-initiated-a-team-discussion">Initiated a team discussion</h3>
<blockquote>
<p>Conflicts are inevitable. Avoid them and they will eventually you find anyway</p>
</blockquote>
<p><strong>Soft skills</strong> is one of the most important skills in life, and transcends any kind of professional work, so it makes sense for everyone to have a certain level of proficiency at it.</p>
<p>I would say that as a person and a software engineer, soft skills has not been one of my strengths all this while, and that is why it is one of my priorities for my professional life.</p>
<p>Among incidents which involve conflict resolution, intra and inter team clarifications, one of them stood out.</p>
<p>There was a disagreement between the senior engineer and I regarding the approach for API versioning. My approach was to add <strong>endpoint-specific</strong> API version URL path, i.e. <code>/v2/some-api</code>, the senior engineer's approach was to add <strong>system-wide</strong> API version in request header, i.e. <code>api-version: &lt;api-version-here&gt;</code>.</p>
<p>Both of us debated about the benefits and drawbacks of the both approaches over slack and in person, and are unable to accept that the other person's approach is much more superior in terms of scalability and maintainability. Even with the CTO roped into the discussion, it resulted in a stalemate because none of us have worked with both approaches before to be able to give an unbiased assessment.</p>
<p>After a few days of back and forth discussion that led to no outcome, I decided to get the rest of the engineering team's input and called for a meeting. Both the senior engineer and I presented our cases and argued for the benefits and drawbacks, which I will summarise below:</p>
<h4 id="heading-api-versioning-via-url-approach">API versioning via URL approach</h4>
<p><strong>Benefits</strong></p>
<ul>
<li>Failures are detected earlier in the request response cycle at API gateway</li>
<li>Able to track the version of each API endpoint independently</li>
</ul>
<p><strong>Drawbacks</strong></p>
<ul>
<li>Duplicate entries in API gateway</li>
<li>Quick and dirty implementation, may not scale well</li>
<li>May result in application logic duplication if it is not well thought out</li>
</ul>
<h4 id="heading-api-versioning-via-header-approach">API versioning via header approach</h4>
<p><strong>Benefits</strong></p>
<ul>
<li>Adhere more closely to HTTP design guidelines</li>
<li>No duplicated entries in API gateway, code duplication in backend services</li>
<li>Clients can use a single global API version, reducing overhead to keep track of versioning for specific endpoints</li>
</ul>
<p><strong>Drawbacks</strong></p>
<ul>
<li>Failure detection is shifted upstream to backend services. An improper logic in handling missing/invalid API version break all requests coming from clients</li>
<li>Require additional effort to make sure that the correct logic is used for different endpoints with different breaking versions, to prevent wrong code paths from being triggered, causing undesirable behaviours</li>
</ul>
<h4 id="heading-debate-outcome">Debate outcome</h4>
<p>After every other member, besides the senior engineer and I, had shared about their experience and opinion, they took a vote which results in an even split between both approaches.
At this stage, it was clear that the merits and drawbacks for both approaches are rather balanced and the team does not have a strong preference towards one.</p>
<p>Before deciding on an approach, we listed down the criteria for a good design and agreed that no APIs are always stable, therefore proper documentation and deprecation of APIs need to be accounted for.</p>
<p>Given the fact that we are under time constraint, none of the engineers belongs to "know-it-all" category of programmers, and we don't believe that there will be a whole lot of breaking APIs over the next couple of years, therefore we decided to go with the header approach.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654347533928/jnVy40VdG.jpeg" alt="group of people putting hands together" /></p>
<h3 id="heading-optimisations">Optimisations</h3>
<blockquote>
<p>Premature optimisation is the root of all evil. Intentional/ignorant non-optimisations is however a greater evil</p>
</blockquote>
<p>As software engineers writing applications in high level programming languages, we get to enjoy the productivity that they bring and are able to push features out to production in a shorter time. However, there is a tendency to gloss over resource usage and performance implications, especially for junior engineers.</p>
<p>It is important to write software with resource planning and performance/cost optimisation at the back of the mind, rather than rushing the code out and leaving it up to the runtime to hopefully sort things out themselves, a.k.a <a target="_blank" href="https://thesavvylife.com/the-perils-of-throwing-money-at-a-problem/">throwing money at a problem</a>.</p>
<p>The ability and foresight to architect a solution with specific performance requirements for certain business critical functions, anticipate possible issues, design a plan to tackle them, keeping in mind performance cost tradeoffs, will most likely save precious time and money further down the road.</p>
<p>Such things usually comes with experience. <strong>e.g.</strong> Use a JSON field to store user preference in MySQL instead of 10 diffferent columns, which could possibly increase in the future.</p>
<p>However, be careful not to fall into the trap of premature optimisation, especially if the performance/cost gains are not tracked, the benefits are not clear, or the solution itself does not solve the actual problem and may create further problems:</p>
<ul>
<li>Moving a few lines of code from a function into the main function to save the cost incurred on a function call.</li>
<li>Using redis to speed up queries instead of using proper indexes in RDBMS</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654347574005/9qErbOuxS.jpeg" alt="race track" /></p>
<h2 id="heading-bad-news">Bad news</h2>
<p>After all the great things, let's talk about the other side because not everything is perfect.</p>
<h3 id="heading-timezone-unaware">Timezone unaware</h3>
<blockquote>
<p>UTC is not the cure-all to timezone difference</p>
</blockquote>
<p>The first major mistake was the failure to take timezone into account when developing the application. What happened was that the user's time input was taken in their timezone, submitted to the server and converted to UTC, and finally converted to the merchant's timezone to search for availability.</p>
<p><a target="_blank" href="https://giphy.com/gifs/disney-frozen-review-WrNfErHio7ZAc">via GIPHY</a></p>
<p>What should happen, instead, is to search for the timeslot directly without timezone conversion. For example, If I am in Singapore and selects 8PM, the server should search for 8PM timeslots for all merchants, independent of end-user and merchants' timezone. The results should then be displayed in the merchants' timezone.</p>
<h3 id="heading-accidental-deletion-of-database">Accidental deletion of database</h3>
<blockquote>
<p>I dropped all the tables in the staging database and not realise it until 15 minutes later</p>
</blockquote>
<p>One of the greatest sins in the world of software is to delete a production database. I have fared slightly better, because I accidentally wiped out a staging database while I was multitasking like the hero I thought I was.</p>
<p>What happened was I replaced a local database by dropping all tables and running the scripts to recreate them, which is fine. What went wrong I had <strong>3 connection tabs</strong> opened in MySQL Workbench, 1 for local, staging and production.</p>
<p>I was rapidly switching between local and staging to check the database schema, and the next thing I did was to drop all the tables in the staging database and not realise it until <strong>15 minutes</strong> later.</p>
<p>What followed was an immediate restore to the last database snapshot, and everything went back to normal. Things would have been so different if I had deleted a production database instead.</p>
<p><a target="_blank" href="https://giphy.com/gifs/fallontonight-jimmy-fallon-tonight-show-concerned-look-lS0hPtkYkayarDcz6u">via GIPHY</a></p>
<p>After this mistake, which could potentially be much worse, I learned to slow down and be more careful when dealing with databases.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654347887764/l9TtY1zsJ.jpeg" alt="delete power return button on macbook" /></p>
<h3 id="heading-jwt-tokens-expiry">JWT tokens expiry</h3>
<blockquote>
<p>Access token and refresh token were set to expire at the same time?!</p>
</blockquote>
<p>According to standard software engineering practices, my team uses JWT to authenticate and authorise access to our API services.</p>
<p>Initially, the access token was set to 90 days expiry and refresh token was set to never expire.</p>
<p>The problem came sometime later when the refresh token was somehow set to also expire after 90 days. This problem took us some time to catch because of several lapses.</p>
<p><strong>Gaps in mobile application</strong></p>
<p>First, the mobile application did not have a fallback when the refresh token request fails, and it will <strong>fail silently</strong>, manifesting as no data showing up on the application no matter what you do. So any user interactions will not be meaningful after 90 days, even though the application is still working, unless the user logs out and log in again.</p>
<p><strong>Gaps in alerts</strong></p>
<p>Second, the alerts for JWT failure via <strong>AWS lambda authoriser</strong> were not configured properly. It was set to trigger when the number of failed requests surpasses a certain threshold. However, the traffic was not high enough to trigger this alert</p>
<p>After identifying the problem, and having a quick discussion, we applied a quick patch as a temporary fix, so that users can still continue to use the mobile application, and designed a long-term solution to fix this properly afterwards.</p>
<h3 id="heading-improper-monitoring-configuration">Improper monitoring configuration</h3>
<blockquote>
<p>No PagerDuty calls mean everything is perfect right?</p>
</blockquote>
<p>This point is related to the previous point about lapses in alerts. My team uses <a target="_blank" href="https://www.datadoghq.com/">Datadog</a> extensively for its logs management, metrics tracking, and monitors and alerts.</p>
<p>We have set up a bunch of monitors to send us alerts via slack integration for API level failures. For service level failures which are more critical, <a target="_blank" href="https://www.pagerduty.com/">PagerDuty</a> integration is used to send alerts to our phone for emergency.</p>
<p>So around 2 months after launch, there were no PagerDuty alerts at all, despite multiple API failures, containers crashing occasionally. No one suspected anything because there were no obvious signs of improper PagerDuty configuration.</p>
<p>This problem was discovered when I caused an outage in search service because I was tweaking the domain path in AWS API gateway, and for some reason the domain path for search service changed to an invalid value and I saved the change without noticing it.</p>
<p>Luckily, the <strong>Datadog</strong> monitors picked that up and alerted us via slack, which resulted in a swift recovery. This lead us to the discovery that the <strong>PagerDuty</strong> integration was set up wrongly because it should have been triggered when a service is down.</p>
<p>The impact of this incident was that the search service was down for around <strong>12 minutes</strong>.</p>
<p>By now, it is clear that not only are sufficient monitoring and alerts important, but they should also be tested to ensure that they work in the way that we expected them to, and not let false negatives slip through.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654348096907/MSuVAYRCq.jpeg" alt="performance analytics" /></p>
<h3 id="heading-gaps-within-the-engineering-team">Gaps within the engineering team</h3>
<blockquote>
<p>Move fast, fail fast, except don't fail too much to the point you can't recover</p>
</blockquote>
<p>The engineering team of 7 was built to allow individual members to run at top speed, which proved to work well as we released 3 products within 5 months of intensive work. However, upon deeper examination of the work processes, a few but significant gaps can be found.</p>
<p>First, the engineering team was split according to their roles: backend, web, mobile, infrastructure. While the engineers within their own role are proficient and built features at great speed, there was significant slowdowns for system-wide workflows that bridge multiple roles.</p>
<p>An example would be the user sign up journey that triggers an email notification asking users to click a <a target="_blank" href="https://branch.io/">branch.io</a> link to verify their email, which brings them to the website to complete the verification, and displays a button with <strong>branch.io</strong> link to open up the mobile app.</p>
<p>In the above examples, there are 4 components of the system at work: mobile, backend, web, branch.io. </p>
<p>The team implemented this workflow as a series of independent work with the other component, e.g. mobile and backend, backend and web, web and mobile, which seemed fine, until we received a <strong>customer complaint</strong> from the product team that the verification link in the email doesn't work, and this was just 1 day after launch.</p>
<p>It was later determined that the <strong>branch.io</strong> setting for the website was not updated because it had to be done after the mobile application went live. Apparently, none of the team knew about this except the engineer working on the web.</p>
<p>A possible reason as to how to this could happen could be that was that the team did not have a thorough understanding in terms of the end to end user registration workflow.</p>
<h3 id="heading-gaps-between-engineering-and-product-team">Gaps between engineering and product team</h3>
<blockquote>
<p>Humans are by nature social animals</p>
</blockquote>
<p>I feel that communication gaps between engineering and product team is one of the greatest challenges in my work so far, and is one of the areas that still needs more work on.</p>
<p>This is an issue that happens anywhere, that has also been debated about back and forth, with discussions in favour of engineers while bashing product managers and vice versa.</p>
<p>On the other hand, there are also well thought out discussion on how both teams can work well together, such as this by <strong><a target="_blank" href="https://www.theengineeringmanager.com/growth/the-engineering-product-relationship/">the engineering manager</a></strong>, <a target="_blank" href="https://blog.asana.com/2017/10/product-managers-engineers-develop-great-relationship/">asana</a>, <a target="_blank" href="https://www.intercom.com/blog/product-managers-should-not-build-the-roadmap/">intercom</a>.</p>
<p>These are what I found to be helpful in the product engineering collaboration:</p>
<p><strong>For engineers</strong></p>
<ul>
<li>Have an <strong>active voice</strong>, raise questions and clarifications as soon as possible rather than deferring them.</li>
<li>Do your homework and read up on the product requirements beforehand. Err on the side of <strong>asking</strong> too many questions, because many engineers are rather reserved, and that includes me.</li>
<li>Advise and update effort estimation on non-trivial work. The purpose is to communicate the effort required and implications for the system and roadmap</li>
</ul>
<p><strong>For product managers</strong></p>
<ul>
<li>Be more <strong>involved</strong> in product planning by showcasing research, demonstrating motivation and value proposition of features, and how they fit into the whole UX.</li>
<li>Have accurate and <strong>up-to-date</strong> information on product requirements</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1654348441406/eMRWsToK8.jpeg" alt="man shouting at telephone" /></p>
<h2 id="heading-closing">Closing</h2>
<p>Finally, I want to close this off with a spirit of gratefulness, to give thanks to the people that have shaped my work environment and daily work.</p>
<p>There are many more great things to come, some of which include multi-region and multi-lingual website deployment, domain names and SEO implications, multi-region cloud infrastructure deployment.</p>
]]></content:encoded></item></channel></rss>