<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shaung Cheng on Medium]]></title>
        <description><![CDATA[Stories by Shaung Cheng on Medium]]></description>
        <link>https://medium.com/@shaungc?source=rss-67d8f791b414------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yJsKck-rOXwBkrvltDV3Mg.jpeg</url>
            <title>Stories by Shaung Cheng on Medium</title>
            <link>https://medium.com/@shaungc?source=rss-67d8f791b414------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:37:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shaungc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Things you should know before using AWS SQS]]></title>
            <link>https://medium.com/codex/things-you-should-know-before-using-aws-sqs-5a6d57fb1c9a?source=rss-67d8f791b414------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a6d57fb1c9a</guid>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[queue-system]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Shaung Cheng]]></dc:creator>
            <pubDate>Sat, 06 Nov 2021 09:53:04 GMT</pubDate>
            <atom:updated>2021-12-17T20:14:34.816Z</atom:updated>
            <content:encoded><![CDATA[<h4>Several gotchas to be aware of so you can enjoy SQS scalability without surprise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yEb5-5jzty581qpv" /><figcaption>Photo by <a href="https://unsplash.com/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>SQS</h3><p>As SQS being part of serverless architecture — AWS makes it so easy for you to scale sending hundreds or thousands or way more messages, forget about choosing instance size for message broker. But that comes with a cost, and you should know these tricky things before putting your bet all in it.</p><h4>Tricky #1: sendMessage() is not “synchronous”</h4><p>Even if the function call finishes, it doesn’t guarantee the following receiveMessage() will get the message you just sent. The entire SQS system is a distributed one, so nothing guaranteed in terms of timing. However, long-waiting will probably be rare and you will get the message farely quick most of the time. Still, this delay still may occur, even if you set a high receive message wait time. Setting a wait time as high as the maximum 20s won&#39;t completely avoid this — you’ll get surprised that from time to time, that long 20s is still not enough for SQS to get your message ready in the queue.</p><p>Recommend: use polling to make sure messages eventually get processed</p><h4>Tricky #2: Messages in Queue are non-determinstic</h4><p>It&#39;s very hard to determine if a queue is really ”empty” at a given time point. Even if you stop sending messages, it’s not easy to determine whether a queue is completely drained. The AWS doc suggests you keep polling the queue for 10 minutes with several stats consistently yielding zero, then you can be sure the queue is fully drained.</p><p>Recommend: if you really need to know a queue is emptied or not, use a database to keep track of records.</p><h4>Tricky #3: Blocking issue in FIFO queue</h4><p>One of the first few things to decide when using SQS is to choose a Standard or FIFO queue type. While FIFO queue gives you ordering guarantee, it comes with a cost and has some critical constrain.</p><p>The problem arises when you call receiveMessage() and decide to “put a message back in the queue” — the only way is to not delete it and ignore the message. The message will wait by visibilityTimeout seconds, then it’ll show up in queue again. During this waiting, what happens when newer messages come in? You bet — in order to maintain the FIFO ordering, SQS effectively blocks the entire queue and not letting receiveMessage() calls access any messages.</p><p>Recommend: choose MessageGroupId as needed, so while messages in a certain id is blocked, the queue can still deliver messages of other ids. Or, you may just use Standard type queue if your message won’t depend on previous message.</p><p>And that’s all about the tricky parts. Once you find ways to workaround with them, it’s a breeze to enjoy the high throughput and simplicity that SQS offers, comparing to other options like RabbitMQ that requires you to run a 24/7 server instance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a6d57fb1c9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/things-you-should-know-before-using-aws-sqs-5a6d57fb1c9a">Things you should know before using AWS SQS</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How it feels like using DynamoDB?]]></title>
            <link>https://medium.com/codex/how-it-feels-like-using-dynamodb-1c69fb748b29?source=rss-67d8f791b414------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c69fb748b29</guid>
            <category><![CDATA[schema-design]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Shaung Cheng]]></dc:creator>
            <pubDate>Thu, 08 Jul 2021 08:50:46 GMT</pubDate>
            <atom:updated>2021-09-23T06:50:43.977Z</atom:updated>
            <content:encoded><![CDATA[<h3>What I wish I knew before using DynamoDB</h3><h4>Considering to go for DynamoDB? You should know these search limitations beforehand.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaagGIgrhPeEGpoYH2CBrQ.jpeg" /><figcaption>Partitioning of data, one of the ways to build distributed datastore system</figcaption></figure><p>DynamoDB’s on-demand billing is very, very tempting. You get charged per request, not the 24/7 server up time. No need to choose an instance size— you get the almost “infinite” scalability for free. As a NoSQL database, DynamoDB is document-style, no-schema object store. Everything seems much much flexible and simpler.</p><p>But I got surprised when I found I can’t search data the way I used to do it. I came from Postgres, accustomed to linking columns between tables, storing structured, compacted data. When I tried to search in DynamoDB, there’re so many quirks and limits — why can’t I do something that is so trivial &amp; common?</p><p>Without further ado, let’s look at what to watch out when you query in DynamoDB. I wished I knew beforehand. I’m sure they’ll blow your mind (mine definitely did).</p><h3>Annoying limitations on query</h3><p><em>Spoil alert: it’s more of inconvenience than limits</em>.</p><h4>Limit #1: You can’t change a field if you need to search by it</h4><p><em>(To be more accurate, for “search by” I mean querying by the field)</em></p><p>In SQL, you query by WHERE field1=value1 AND field2=value2 AND field3=value3 .. and as many fields &amp; conditions as you want like it’s entirely free. Of course, you go head update field1 or field2 of that entry in the table if the app needs it, what’s the big deal with that? Except primary key, I feel entitled to have full control over any field values!</p><p>You can’t do that in DynamoDB. If you’re gonna query by field1 , you better plan field1 to be read-only — once the object created, you cannot update this field! What? Ughh!</p><p>Feel so constrained and suffocated? There’s one small window for fresh air: you can remove field1 or add it back. That’s the only mutating operation you can do on a queryable field (I use the term field as it seems more common in SQL, but DynamoDB uses the term “attribute” more often; they’re interchangeable in this post). This is called the “Sparse Index” technique. There’re some important indications of Sparse Index. If the field value needs update, you can only <strong>query in a binary, boolean way</strong> —query either the field is there, or not there.</p><p>You ask: “Shouldn’t this be a must-have feature?! I’ll need to update a field, AND we need to query by it.” For example, you have a field called status. Its value could be Running , Failed or Completed , this field must be able to update, and we need to query on status for app’s search function to work! You can, Sparse Index can serve this need but extra work is needed. It works like this: you create another field called isRunning , isFailed or isCompleted , you can now query on these fields to search for the items you want. Of course, you’ll need to maintain these additional fields by removing or adding them as you update status value.</p><h4>Limit #2: Only up to two fields are searchable</h4><p>What’s even worse: one of them can only do “exact match” search, and you have to always specify this one when query, can’t be optional! This is the “partition key”, like a primary key in SQL.</p><p>You actually only have one field allowed for flexibility, the “sort key” — you can use all the great = , &gt; , &lt; , BETWEEN , STARTS WITH operators, …, and it’s optional. But remember, only one field like this is allowed for query! Seriously?!</p><p>Because of this huge limitation on query, you are forced to combine various alternative ways, try everything you can do, as long as it gets the data your app needs within a reasonable time. Yes, now your DynamoDB schema design needs to brainstorm like hell.</p><p>Alternatives I know so far (this list may grow as I keep learning from my journey)</p><ul><li>After querying by the 1~2 fields, does the result size go down to just a few items? If so, it’s now appropriate to use a scan to filter on further more fields.</li><li>Do we really need to query by that many fields? The app probably don’t need to filter on everything. Give me more details on the app access pattern, or even negotiate it, as long as the important users needs are served</li><li>Create multiple GSIs (Global Secondary Index), so even if you can only query on <strong>up to two </strong>different fields in a GSI, hopefully with multiple GSIs, they can cover most of your app access pattern (still, query on more than two fields at the same time is not possible)</li><li>Concatenate several fields into one could help query on more fields. See example in “<strong>Dilemma in Selecting Partition Key</strong>” section.</li><li>… more ways?</li></ul><p>Usually, a field of timestamp as sort key is effective enough for trimming down the result query size. Then, using scan or other techniques to further filter on other fields would be OK.</p><h3>More annoying facts…</h3><p>Let’s talk about tricky topics when designing DynamoDB schema.</p><h4>Dilemma in Selecting Partition Key</h4><p>Cardinality — a term to describe the degree of variation of a collection. High cardinality, lots of variations. Low cardinality, only a few kinds.</p><p>People suggest in order to avoid hot key — which means one data partition got accessed too often comparing to other partitions, and performance could get clogged. So instead, you want to choose field of high cardinality as the partition key. However, huge drawback is it could make it hard to query — query always needs you to supply the exact partition key (“exact match” mentioned above). What’s wrong with that? <strong>If a field is of high cardinality, chances are it’s not easy to know its value when you need to search.</strong> An extreme case is UUID — max cardinality, but almost useless for query or search except a single-item Get operation.</p><p>You ask: well can I choose a field as partition key to aid query — to help narrow down the results? Yes you can, but with cost. One technique is to concatenate multiple fields into one. For example, you have an object that has fields property1 , property2 , property3 , property4 . You can concatenate several of them, say, the first two fields, as partition key, like property1Value-property2Value . Now when you query, you can query by property1 and property2 for free, achieving WHERE property1=property1Value AND property2=property2Value . Wonderful! Right? Hang on, does the concatenated property1Value-property2Value provide enough cardinality? If not, then uh-uh, hot key problem. If yes, next the 1st problem is you have to <strong>always</strong> <strong>specify</strong> both property1 and property2 for query, can’t be optional like only WHERE property1=property1Value or WHERE property2=property2Value . 2nd problem is if you’re selecting partition key for the base table, these fields must have non-empty value for all items. This could be annoying since you already prepared to go flexible and schemaless with NoSQL and now you’re saying we need some fields to be non empty?!</p><p>What people often do is creating GSI to tackle with the 2nd problem —in a GSI, partition key can be empty. So 2nd problem solved. To tackle the 1st problem…. you just have to live with it, that’s the cost for using partition key to query. So, you can choose the partition key wisely, think about whether to concatenate or not, if yes then how many fields to concatenate, because you’ll need to always specify them in query once concatenating.</p><p><strong>I’d say when selecting partition key for base table, forget about aiding query, just use UUID or a field that you’re sure all items have non-empty value on. Then, since UUID is useless for query, you create GSIs so that you can select other two fields to query on</strong>.</p><p>Or, if you do want to use partition key to query, which is also inevitable in GSI, you always need partition key to query anyway, so you selected some low cardinality field as partition key, like a “status” field of value either “provisioned”, “approved” or “published”, then you worry about hot key. I found this quite confusing, <strong>on one hand query mandates partition key and can only do exact match, so you want to select a field with not too many variations to make the app’s search flexible &amp; easy to use, but on the other hand this leads to hot key problem.</strong> Boom, is DynamoDB even usable? Well, you might just forget about hot key. I saw some articles on AWS blog saying DynamoDB eventually will do data node replication and load balancing for you when it detects a particular partition gets lots of attention. This offer is true for GSI, but not LSI (Local Secondary Index).</p><h3>Not-so-true DynamoDB Best Practices</h3><p>Now let’s talk about pitfalls — you thought they are “best practice” to follow, yet, not necessarily so!</p><h4>Don’t use scan</h4><p>Scan is notorious — since it goes through every database item — it blocks the database performance, it’s costly, slow, it’s not scalable. Query is fast, efficient.</p><p>But it doesn’t mean we should exclude using scan, even if we are seriously thinking about scalability and performance. This is true especially when you have complicated access patterns and data shape.</p><p>So using scan is fine, just, make sure the items to scan are “not too large”. When it’s in the middle — kind of large, but not too large, or you’re not sure about the future — you may still try your best to consider query (indexing) or other alternatives first.</p><p>Scan operation is not only used by Table.scan() , but also by filtering on query Table.query(FilterExpression=...) . <strong>A common way is first narrow down the result size by query on two fields (partition key, sort key), then apply a filter (scan). Of course, the result size better be small enough after your two-field querying</strong>. So, which two fields to select for query is crucial, that’s probably the biggest part where you will struggle, ask more about the app’s the access pattern, and go back and forth. Hopefully creating GSIs will give you enough flexibility.</p><p>And that’s it! The “quirks” when using DynamoDB. They do not limit you from achieving very complex query, but there’re extra cognitive load required, which is the main point I wanted to show you in this post. Lastly, it definitely takes time to get rid of SQL way of doing things like foreign keys and tables. It doesn’t have the convenient, flexible query SQL provides, but then we should ask ourselves: do we really need all of them? What can we let go? You probably heard of NoSQL forces you to plan your app access patterns AND even the scale of each pattern. Because you’re going to deal with these big constraints.</p><p>At the end, I give in — perhaps the inconvenience are the cost of scalability and performance that DynamoDB offers out of the box. And all that above is a quick takeaway of DynamoDB for now. This brainstorming process happened when I finally had a chance to orchestrate a DynamoDB table from start to end for consumer product.</p><p>I hope this post gives you an idea of what you’ll need to deal with if you come from SQL and decide to go for DynamoDB. For me, more post will come once I get more insight along the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c69fb748b29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/how-it-feels-like-using-dynamodb-1c69fb748b29">How it feels like using DynamoDB?</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Redux Learning Experience]]></title>
            <link>https://shaungc.medium.com/my-redux-learning-experience-de09f5150adb?source=rss-67d8f791b414------2</link>
            <guid isPermaLink="false">https://medium.com/p/de09f5150adb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Shaung Cheng]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 17:31:50 GMT</pubDate>
            <atom:updated>2019-09-19T16:32:57.932Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recommended Steps to Get Started with React, Redux and Typescript</h3><h4>Based on my redux learning experience</h4><h4>TL;DR</h4><p>For those who are in a hurry and just want the recommended learning steps, you can jump to the last section “Suggested Pathway”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*SRL22ADht1NU4LXUeU4YVg.png" /><figcaption>Credit from <a href="https://commons.wikimedia.org/wiki/File:Redux.png">WikiMedia Commons</a></figcaption></figure><p>In this article I will talk about why I came to redux, and share my learning experience integrating redux in a react typescript project. This is a high level reflection about the process so no code blocks — but the resources &amp; articles I included at the end will have a lot of them, feel free to check them out!</p><h4>Background &amp; Context</h4><p>I’m currently in the middle of developing two projects — <a href="https://github.com/rivernews/appl-tracky-spa">appl-tracky</a> and <a href="https://github.com/rivernews/BlueBucksDinerReactNative">blue bucks diner</a>. One is web-based where I will use Redux, and the blue bucks diner (alias: BB!) is a mobile app. Both are benefited from my research in AWS for the pass one month so they now have auto-scaled, containerized backend server on AWS. I wrote a <a href="https://medium.com/@shaungc/protect-your-aws-ecs-service-behind-application-load-balancer-alb-and-create-them-by-terraform-6db816d329f7">Medium article</a> for this in case you are interested in the infrastructure. More recently, I’ve been focusing on appl-tracky, whose frontend uses React + Redux (and Typescript) — a very popular combination.</p><p>I often heard many people say don’t use redux if just someone told you to. Exactly and that makes a lot of sense. But when should we use it? Before knowing this, I just sticked to setState() and it kind of work well. But I always have a question as a person who came from Angular: what is the equivalence of Service in React? In Angular, Service is singleton and can be injected in whichever component that needs that data.</p><h3>I think I need Redux…!</h3><p>The time where I feel I need redux is when I’m dealing with user login. After all, many views will be conditional depending on login status, who logged in, …etc. Otherwise, basic info like isLogin or userName will have to be passed around repeatedly. In short, I need a global state management so badly. Oh and one more thing, I recently just learned RxJS is the Angular style of state management, and it&#39;s interesting to see how different framework deal with data syncing across different components.</p><h3>Journey to Learning Redux</h3><p>I won’t talk much about the details of redux — after all this is not a tutorial, but I want to share my learning experience, some personal thought, and a list of recommended pathway to learn React + Redux + Typescript.</p><p>First, React is open, un-opinionated which contrasts to Angular. For new comers, this could be intimidating, because essential pieces of functionality is scattered over different tools. There’s a big chance that the documentation or tutorial you are looking at has a different choice of tooling and does not fit your tool stack.</p><p>For example, in appl-tracky, I use React + Typescript, and now I want to integrate with Redux. While there are crazy stuff all over like redux thunk, saga, ...etc, as a new comer - always start with the basic - I have that in mind. So just React, Typescript, and Redux. Nothing more. Simple, right? ...not at all!</p><h3>Start researching — Official Documentations</h3><p>So first, obviously, I visited redux official site and read their tutorial. They mentioned they are un-opinionated and emphasized they can be used in various kinds of framework. OK, got that. The quick start guide is pretty simple, just action objects and a reducer function. Then, they talked about dispatch, and then subscribe, but added that you typically won&#39;t do subscribe and the framework should have some mechanism handling this. I have no idea what that mechanism is, but that&#39;s where I start feeling I&#39;m missing something. And I realized, gosh, this quick start is only for Redux + vanilla JavaScript. Of course it is, it&#39;s the first guide in redux official site! Based on my previous experience, however, different situation could have very different configuration, and settings for Redux + VanillaJS and Redux + React can be totally different. What is the React way to setup Redux?</p><p>I feel a bit vigilant here, because I’m worried what if I’m just wasting my time looking in the wrong place? I think maybe I should search for an article that matches our stack exactly — React, Redux and Typescript. So I start searching, and this comes first in the search: “<a href="https://github.com/piotrwitek/react-redux-typescript-guide#redux---typing-patterns">Github: The complete guide to static typing in “React &amp; Redux” apps using TypeScript</a>”. Sounds great, hopefully it will explain from the basic and the rationale behind different parts of it. But I see things like sagas, middleware, and a lot of code blocks which I have no idea which file they should be in.</p><p>So I moved on, and the next search result is actually Redux official’s “<a href="https://redux.js.org/recipes/usage-with-typescript">Usage with TypeScript</a>”. It was easy to follow, at first. Since I now have some idea of the redux components — reducer, action and store, mostly it just adds typing to them. Then down to section “<a href="https://redux.js.org/recipes/usage-with-typescript#usage-with-react-redux">Usage with React Redux</a>”. I was a little panic then concerning that, is this a new tutorial? It turns out it continues the setup above so I can keep following. At the end I was able to setup actions, reducers, store, and App Props in Typescript. But where is redux store? The page didn’t mention it. How do I use the global store in a component? That was where I got so confused. The following section “Usage with Redux Thunk” just sound terrifying to me (middleware? Asynchronous orchestration? I just want to setup React + Redux + Typescript…!). But even that, that section doesn’t seem to cover store, and I did not know why. But one thing is for sure: I have to find another place to figure out how to setup that redux global store, as well as access it from react components.</p><h3>Dig into the Community</h3><p>And I started reading articles that use React + Redux + Typescript, many are from Medium. But the difficult part is, some has their own style of configuring things, or the steps are not clear (e.g. which file does this code block belongs to), or uses a bit complicated example with extra tools like saga, thunk, doing dispatch and async stuff in action creator, which I feel did not help me cover the basics. This is exactly the hardship I feel as a new comer when learning new technologies. I eventually found this <a href="https://blog.usejournal.com/using-react-with-redux-and-typescript-c7ec48c211f6">Medium post</a> from Christopher Beards that wrapped up and ended my hours of researching. The most valuable part is seeing how he sets up redux store, connect it to component and access the store using props.</p><p>But that’s not the end of this redux journey. I still don’t know how to “write back to store”, that is, dispatch action to global store. But I feel I found some really good readings, and I’m really close to get there now!</p><h3>Suggested Pathway</h3><p>At the end I want to summarize my recommended path to learn React + Redux + Typescript. Because one tool depends on one another, so the ordering matters. Below is a step by step suggestion to pick things up.</p><p><em>Side Note: I included my own exploration trajectory as numbers at the end of each step. Numbers with a mark like “(~6.)” mean it’s not exactly clear when I got it during the process reading countless articles, but the “ah-ha” moment happened approximately in that order.</em></p><h3><strong>Step 0 — Learn React if you don’t know it yet</strong></h3><p><strong>What to know</strong>: Installation using create-react-app, Components, JSX syntax, how props work, and local state management.</p><p><strong>Recommended tutorial<br></strong>Installation and basics are covered in <a href="https://reactjs.org/docs/hello-world.html">React Official</a>. I generally recommend the React Official site, their examples are clear, simple enough and well explained. Particularly:<br>Writing class-based component: <a href="https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class">React Official</a><br>JSX syntax: <a href="https://reactjs.org/docs/introducing-jsx.html">React Official</a></p><h3><strong>Step 1 — Give a taste of redux first </strong>(1.)</h3><p><strong>What to know</strong><br>What actions &amp; reducers do and how they look like.</p><p><strong>Recommended tutorial</strong><br>“<a href="https://redux.js.org/introduction/getting-started">Getting Started with Redux</a>” @ Redux Official site</p><h3><strong>Step 2 — Know practices and conventions using Typescript with React </strong>(~6.)</h3><p><strong>Recommended tutorial<br></strong>If you are like me coming from Angular, you already know the syntax. But there’re some React-specific things you might want to check out as well; otherwise you might get confused along the way, e.g., start using interface instead of PropTypes.</p><p><strong>Recommended reference</strong><br><a href="https://github.com/Microsoft/TypeScript-React-Starter#typescript-react-starter">Microsoft Guide @ Github</a>.</p><h3>Step 3 — Know how to setup redux in react (~3.)</h3><p><strong>What to know</strong><br>Learn react-redux: You know how to setup reducer and action in step 1, now focus on how to setup redux store, and access it from react components.</p><p><strong>Recommended tutorial</strong><br><a href="https://blog.usejournal.com/using-react-with-redux-and-typescript-c7ec48c211f6">Christopher’s post</a> covered this. It’s a Typescript example, however. If you feel not ready to dive into Typescript yet, feel free to find tutorials for beginners specifically for react-redux without other tools.</p><h3>Step 4 — Put all together I (react/redux/typescript) (2.)</h3><p><strong>What to know<br></strong>How to add typings to react-redux for actions and reducers.</p><p><strong>Recommended tutorial</strong><br><a href="https://blog.usejournal.com/using-react-with-redux-and-typescript-c7ec48c211f6">Christopher’s post</a> covered this.</p><h3>Step 5 — Put all together II (4.)</h3><p><strong>What to know<br></strong>Configure redux’s store, glue it to our react component tree, and setup component props to have access to store. All with typings — the Typescript way doing it.</p><p><strong>Recommended tutorial</strong><br><a href="https://blog.usejournal.com/using-react-with-redux-and-typescript-c7ec48c211f6">Medium post</a> from Christopher Beards. It’s clear, example isn’t too complicated, and covers pretty much the details from setting up action/reducer/store, and get values from store by component props.</p><p>It wasn’t clear to me when the articles configure store in index.ts, it&#39;s not the file ./store/index.ts, but the React project root src/index.tsx, just next to your App.tsx.</p><p>The key to “glue” redux store to your component’s props is using the connect() function. But there’s one tricky part about exporting the connected component and importing it in another place. In short, you import without braces. For more details, refer to this short article <a href="https://daveceddia.com/redux-connect-export/">“How to Export a Connected Component” by Dave Ceddia</a>.</p><h3>Step 6 — Put all together III (5.)</h3><p><strong>What to know<br></strong>Writing/updating the react-redux store, i.e., dispatching actions. Also learn the popular react pattern— “Container VS Component”.</p><p><strong>Recommended tutorial<br></strong>This <a href="https://stackoverflow.com/a/40068198/9814131">StackOverflow post</a> shows it well how to 1) connect dispatch to component, and 2) how to dispatch action in component.</p><p>You’ll need typing as well, which isn’t covered in the StackOverflow post. Quickly lookup how to specify types for dispatch by referring to <a href="https://github.com/piotrwitek/react-redux-typescript-guide#redux-connected-components">this guide on Github by Piotrek Witek</a>. Just look at the code block example particularly how he specifies types.</p><p>Along with figuring out how to glue dispatch to your component, you also want to be aware of the Container Component pattern. This <a href="https://medium.com/@learnreact/container-components-c0e67432e005">Medium article</a> recommended by the StackOverflow post explains it clear.</p><p><strong>Supplementary Readings<br></strong>Look at ways to glue dispatch to your component — <a href="https://blog.benestudio.co/5-ways-to-connect-redux-actions-3f56af4009c8">5 Ways to Connect Redux Actions</a> @ Medium.</p><h3>Closing Thoughts</h3><p>Last but not least: it’s important to start writing code while following the article. Tailor the variable names, function and structure to your own app — it’s a good way to verify that you get the concept and aren’t just copy pasting code. (I do recommend having an app you want to build in the first place, so you have good motivation)</p><p>If you are also a junior or you’re new and also learning React, Redux or TypeScript, I hope this post can resonate some of your experience! Share your own unique learning experience below, I’d love to hear how you think and what you found interesting during the process. As I’m still learning, also point me out if you think something doesn’t look right!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de09f5150adb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protect your AWS ECS Service behind Application Load Balancer (ALB) and create them by Terraform]]></title>
            <link>https://shaungc.medium.com/protect-your-aws-ecs-service-behind-application-load-balancer-alb-and-create-them-by-terraform-6db816d329f7?source=rss-67d8f791b414------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db816d329f7</guid>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <dc:creator><![CDATA[Shaung Cheng]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 02:43:27 GMT</pubDate>
            <atom:updated>2019-03-01T19:28:39.769Z</atom:updated>
            <content:encoded><![CDATA[<p>A small piece of post during the journey starting from zero and diving deep into Docker, AWS Elastic Container Service and Terraform DevOps orchestration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDQrSu1diJf8JwN45ll_rA.png" /><figcaption>The entire journey to deploy docker infrastructure on AWS ECS from scratch.</figcaption></figure><p>This article is a write-up about how to deploy containers using Application Load Balancer. Just as when I was browsing posts, articles online for hours and hours and finally found that enlightening piece of information, I hope this article can do the same to you, and be one another resource out there.</p><p>Junior developers always have a hard time understanding the crazy tools all over the way in the industry. There’re still a lot for me to learn. I’ll make them clear for places where I don’t know what’s going on, or why it behaves that way. It’s largely possible that my understanding is wrong, so please feel free to give me feedback. Let’s discuss DevOps together!</p><p>To clarify, this post is not to walk through how to setup Node.js API, MongoDB and AWS ECS service or task definition (maybe for another post), this post focuses on how to use application load balancer (ALB) with Amazon’s docker container service ECS and setup security settings, also many Gotchas I came across when navigating through the AWS ecosystem.</p><h3>Tech Stack</h3><p>Before we begin, let’s skim through the tech stack so you can see if this fits your case.</p><h4>Local</h4><ul><li>Nginx as primary web server</li><li>Node.js as API server. MongoDB using remote Atlas, so we don’t need to host our own MongoDB.</li><li>Docker</li></ul><h4>Orchestration</h4><ul><li>Terraform to create and update AWS infra.</li></ul><h4>AWS</h4><ul><li>Elastic Container Service (ECS)</li><li>Domain name purchased from Route 53</li><li>SSL Certificate from AWS Certificate Manager</li><li>Application Load Balancer, but only having one service to route to, so always use the / path only.</li></ul><p>You can take a look at the resulting Github repo: <a href="https://github.com/rivernews/bb-rest-api">https://github.com/rivernews/bb-rest-api</a></p><p>We’re skipping pre-setups such as Docker (Docker Compose), Node.js and Nginx. We also skipped preparations on AWS such as IAM, domain name using Route 53, and all hard-coded stuffs in variables.tf and other Terraform files. If you’re looking at the repository for reference, don’t look at the folder terraform-experiments. All used terraform scripts are in terraform directory.</p><h3>Creating Application Load Balancer (ALB): The Frontier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDlXR-czqLSnnIqEzRxCNw.png" /></figure><p>Instead of letting users access the instance’s public domain address or IP directly, we want to let load balancer serve as a single source of incoming request. Then, we can configure ALB to route internally to different web apps. However, in our example, we only have one service (i.e. one app), so our ALB will only forward to the root path /. Multiple services may require slightly different configuration of the listeners on ALB, which we’ll not cover here.</p><p>There are three components for ALB: security group, listener and target group.</p><h4>Security Group</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*bB4Cm-QC4AQKNaKBHjqIDw.png" /></figure><p>Security group is for limiting incoming (called `ingress`) and outgoing (called `egress`) traffic by port, protocol or certain IP source. It can be attached to various kinds of AWS resources, like load balancer, EC2 instance or autoscaling group (which is a dynamic portion of EC2 instances). You can also “limit access by another security group” — this lets you limit the traffic to internal AWS service, which we will apply later.</p><p>For our public-facing ALB, we don’t want to limit to specific IP, since we want the web app to be accessible globally. So we set the source as 0.0.0.0/0. If you want to restrict visitors to certain country, or even certain organization, this is the place to configure.</p><h4>Listeners on ALB</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*8TXQ3g7tDCkZ3JuIr2rVnQ.png" /></figure><p>Load balancer has “listeners” you can add. Listeners can accept incoming http or https request, and decide the following routing behavior, say forward to your web app or redirect to somewhere else.</p><p>I’m not sure why it’s specific to only http and https, after all they are both TCP and are only different by port (80 and 443). Perhaps it has something to do with the Layers — ALB listener is at Application Layer, whereas security group is at Network Layer.</p><p>Here, we set listeners for only HTTPS/443, since we want to block all http connections and only allow https. Since the server will be serving a API for a mobile app, this might be OK. In other case, e.g. a web app, you may want to accept HTTP/80 as well, and redirect to HTTPS so the web app is more available to the users, regardless of what protocol they type on their end.</p><h4>Target Group</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-iN5GJK1p9CGDgFSCG1dw.png" /></figure><p>ALB listener always forward to a target group. Listener and target group, they are pairs. ALB cannot forward directly to your web app — which is something a bit counter-intuitive if you’re new to AWS’s ELB like me.</p><p>Before request can be routed to your web app from ALB, you have to create a target group. You can then `register` your web app in the target group, and your web app is the “target”. Within one target group, you can register multiple web apps, with each using different ports. It’s worth mentioning at this point that, the port number is no longer associate with that port number of the request sent by internet users. This port number is used by the traffic emitted by ALB, which is an internal traffic.</p><p>ALB and target group together serve as a router that routes an incoming request based on its protocol (http or https) to your web app. Your web app is some server like Nginx, Django or Node.js, which again listen at a certain port. The port number you registered in target group has to correspond to the port number of your server app.</p><p>Here, our first layer web server is Nginx and listens on port 80, so we register a target of port 80 in the target group. Also, ALB’s health check happens here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acab2d232d4b853f4996906c9f286344/href">https://medium.com/media/acab2d232d4b853f4996906c9f286344/href</a></iframe><p>We’ll skip the task definition and service part.</p><h3>Protect Our Server and Set Behind ALB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQuGsqk0zpPQC0nrmN_D1Q.png" /><figcaption>See the incoming request from left, which bypass load balancer and attempts to access EC2 instances directly.</figcaption></figure><p>Even if we set our ALB as only listening to HTTP/443, this does not cover the case where an user accessing our EC2 instance’s public DNS/IP instead of the domain name associated with ALB. Access rules to EC2 instance is controlled by EC2 instance’s security group.</p><p>We have several options here:</p><ul><li><strong>1. Reuse ALB’s security group</strong>: we can restrict port to only allow 443 ingress traffic, but this will allow request globally.</li><li><strong>2. Create another security group and set ALB’s security group as the source</strong>: this will let us accept traffic with the same ports as ALB, but limit traffic to only from ALB.</li></ul><p>Option 2 allows our instances to be accessed only from ALB’s traffic, so is much secure and we’re using this option here. Note that now if you also limit port number to 80 for this security group, ECS Service will have trouble accessing the instance (so will the containers reside in it). This might be due to the fact that ALB and ECS Service use dynamic ports range from 32768 to 61000, in order to support routing to multiple services using one single ALB. I’m not super clear about this yet, I’m only sure that limiting to port 80 will give you 503 server temporarily unavailable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d7f567ede3b30e12a77b767690ce21b/href">https://medium.com/media/1d7f567ede3b30e12a77b767690ce21b/href</a></iframe><h3>Executing Terraform Script</h3><p>Once we have all the necessary resources defined in the terraform script, we are ready to execute.</p><p>And that’s it! This is my first post on Medium, and I hope you enjoy it! We certainly skipped many steps in the preparation details. As I understand more about Docker, ECS and the ecosystem, I hope I can share more about them, and help more new comers like me to get started.</p><h3>Reference &amp; Inspiration</h3><ul><li><a href="https://serverfault.com/questions/321820/how-to-allow-elastic-load-balancer-through-port-80-in-security-groups">Stackoverflow: How to allow elastic load balancer through port 80 in security groups?</a><br>The discussion here inspired me of specifying a security group (SG) instead of an IP in SG’s source field.</li><li><a href="https://www.reddit.com/r/aws/comments/8efr6b/aws_ecs_with_elb_and_https/">Reddit: AWS ECS with ELB and HTTPS</a><br>This discussion guided me through how I should configure load balancer and EC2 instance security group.</li><li><a href="https://www.terraform.io/docs/providers/aws/index.html">Terraform: AWS Provider</a><br>Also very useful — the Terraform official doc.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db816d329f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>