<?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 Han on Medium]]></title>
        <description><![CDATA[Stories by Han on Medium]]></description>
        <link>https://medium.com/@hansololai?source=rss-895461d99744------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rEQXR8iDWB7OrcCj8pnOGQ.png</url>
            <title>Stories by Han on Medium</title>
            <link>https://medium.com/@hansololai?source=rss-895461d99744------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:25:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hansololai/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[Graphql Subscription Deep Dive: why is it not popular?]]></title>
            <link>https://hansololai.medium.com/graphql-subscription-deep-dive-why-is-it-not-popular-ad7c103ace22?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7c103ace22</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[graphql-subscriptions]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 02:30:36 GMT</pubDate>
            <atom:updated>2022-04-21T02:30:36.955Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: This is not a tutorial that you can find just by googling “graphql subscription” or look up on <a href="https://www.apollographql.com/docs/apollo-server/data/subscriptions/">apollo server documentation</a>. Using graphql subscription can meet some unexpected difficulties and I have not found any posts talk about it in detail (I only see simple tutorials and code sample and non of them solve my problem). So I decided to write one about why graphql subscription is more difficult and what can we do to improve the performance. I briefly talked about it in a <a href="https://hansololai.medium.com/advanced-graphql-subscription-performance-85f9ab858bbe">previous </a>post, but that was not detail enough.</p><p>The post is split into several sections:</p><ol><li>What is a websocket server look like ?</li><li>Use Background worker to do the expensive work.</li><li>What is the difference between regular broadcast vs graphql pubsub ?</li><li>What can we do to improve graphql pubsub performance ?</li></ol><h3>What is a Websocket Server look like ?</h3><p>Websocket actually just means the connection protocol between browser and server. I think what we actually mean, is a server that keeps live connections with a number of clients, and have ability to receive message and broadcast message to all clients (pub/sub).</p><h4>Basic WSS(WebSocket Server):</h4><p>A barebone websocket server is simple, it just need to keep a list of connections, and whenever it needs to broadcast message, just loop through the list and send message to each of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2daa76a6d54af54205baec3c04ed2696/href">https://medium.com/media/2daa76a6d54af54205baec3c04ed2696/href</a></iframe><p>Simple enough right ? To receive message from client, like a chat app, you could add “on message” in the con , like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af88feb670b0dc61558fb2e373e40987/href">https://medium.com/media/af88feb670b0dc61558fb2e373e40987/href</a></iframe><p>In reality, the place where you broadcast any message (call the publishMessage) function is best to be put outside of a request cycle. In a case if you have a lot of clients, (say a million), simply loop through clients and send message would cause the request cycle to lag quite a bit. The following example is an “not ideal” handling of broadcast:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea62cbd4b386f26e5952339f8005e2f0/href">https://medium.com/media/ea62cbd4b386f26e5952339f8005e2f0/href</a></iframe><h4><strong>Using Redis pub/sub to broadcast asynchronously</strong></h4><p>A common pattern to jump out of this, is to design the system architecture such that the websocket server (handles broadcasting) and http server (handles create user in this example) to be in different machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBPeQFwpxwmD7CoUUKJ7eQ.png" /><figcaption>Fig 1. Two server design for http and wss server</figcaption></figure><p>Note the “Send signal” part should be very fast request compare to calling the publishMessage function and it broadcast asynchronously. This make scaling the servers easier, (If you get a lot of ws clients, add wss server, get a lot of GET/POST requests, add regular servers).</p><p>So how do we “Send signal to broadcast” ? This is the case where we normally use some pub/sub software, such as redis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6308ebe5c69bb917af6e334322939fd1/href">https://medium.com/media/6308ebe5c69bb917af6e334322939fd1/href</a></iframe><p>Obviously in reality, all the clients may be listening to different topics, so there is a redis channel that we could use to separate clients into groups, and send messages to specific groups.</p><h3><strong>Complex broadcast logic in background worker</strong></h3><p>In some case, the broadcast message is not straightforward, it might need some expensive calculations. In this case, we should <strong>NOT </strong>put those calculation in wss server like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a0cca1b5ac15ac43c2d7e2382812aeb/href">https://medium.com/media/2a0cca1b5ac15ac43c2d7e2382812aeb/href</a></iframe><p>Instead, the work should be delegated to background worker:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53758318fddd7afeda619404bfc09086/href">https://medium.com/media/53758318fddd7afeda619404bfc09086/href</a></iframe><p>Moreover, this pattern also have one important benefit: debounce tasks to reduce redundant work. In simple terms, if a background job is triggered multiple times in a short time, the job should only need to run once. This technique was described in more detail in a <a href="https://hansololai.medium.com/post-save-hooks-do-it-right-9c5bf4afe9e7">previous post</a>.</p><h4>Summary</h4><p>An efficient WebSocket server should only handle the connected clients (put in different groups, assign ID to them, can easily search client by ID etc), and broadcast message to clients with the message received from redis. The broadcast and expensive computation should be delegated to background worker.</p><h3>Regular Websocket broadcast vs Graphql Subscription</h3><p>A regular websocket broadcast works as the following figure depicted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*CVa45WhBOIZt8gx8WU4qZA.png" /><figcaption>Fig 2. Websocket Server broadcast diagram</figcaption></figure><p>When an event is triggered, server start a background job to calculate some result, then it is published to redis, which notifies all redis subscribe clients (websocket server), and then server receives the result and loop over all connections (or find the target connection) and send result to client(browser).</p><p>A Graphql server, however, works differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*mJFB9rYt9RgGL4woYcW0vA.png" /><figcaption>Fig 3. Graphql Server how subscription work</figcaption></figure><p>Regardless of what library you use (Apollo Server, Envelop etc). The above figure demonstrate that when an event is triggered, there is no background worker to process some result. <strong>The main reason is that each client, although subscribing to same Rootfield, could be asking for different data.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af3bead2a2edaa104903bdf6b40c9037/href">https://medium.com/media/af3bead2a2edaa104903bdf6b40c9037/href</a></iframe><p>As shown in above code, two queries are both subscribed to the userUpdated event, but they ask for different fields (query2 ask for extra posts data).</p><p>Because of this, Graphql Server must execute each client’s subscription query when broadcasting the event. Which means with n clients, the server need to process n queries. This may have significant impact on the performance and is very different compare to the regular websocket server setup, where all clients subscribe to same data.</p><p>The impact is two fold:</p><ol><li>Spending resource in WS server vs Spending resource in background worker</li><li>Calculate n queries instead of 1.</li></ol><h4>WS Server vs Background worker</h4><p>Obviously, if the computation resource is unlimited, then non of this performance impact matters, just throw in more money and the problem is solved. In general, scaling workers is much easier than scaling servers. If your server is not powerful enough, scaling the server, (add more machines or change to a more powerful machine) is more expensive than scaling the workers. Where a worker could just be any machine that runs a script, triggered by a broker, an extra server would require load balancing, reverse proxy etc. (A broker is a service that allows server to put task in, and broker send the task to workers).</p><p>Therefore, if possible, the ws server should just be a thin layer of “receive result from somewhere, and send to client”, instead of “receive signal, and calculate result, and send to client”.</p><p>However, this rule is hard to be applied to GraphQL server. The reason is that when a client subscribe to server, it also send a GraphQL query that explains the data it request for. If you want to use background worker to calculate the result, the worker will need to know the GraphQL query. Allowing the worker to know the GraphQL query is quite complicated. Not impossible, but complicated.</p><p>You could send the query text as parameter, that is an easy solution, but the query text is usually pretty long, which could eat up a lot of bandwidth for the broker.</p><p>Another option is to store the subscription query of client in database, or using memcache using hash of query as key, then background worker could fetch the query and run it and send the result back.</p><p>The above two options are both feasible ways to redirect the expensive computations to workers. However, the designs are pretty difficult to implement in the current GraphQL framework.</p><p>Let’s take a look at Apollo Doc subscription demo code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*cUJD5b_vKGB3KMkiLigYag.png" /></figure><p>When client subscribe to postCreated field, server create and stores an AsyncInterator object. This object is then triggered, whenever the pubsub framework (in our case, the redis) broadcast a ‘POST_CREATED’ event. Immediately when the object is triggered, server will then execute the resolve function that’s associated with the postCreated field. Using our userCreated as example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e54f57fc5f876b0846453e8c3828bde/href">https://medium.com/media/0e54f57fc5f876b0846453e8c3828bde/href</a></iframe><p>The process flow is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*k1rsJhtk5OlMpmXRGFrNhQ.png" /><figcaption>Fig 4. Graphql Subscription trigger process</figcaption></figure><p>To implement the above two approaches so that we can redirect the expensive calculations to background worker, we need to modify the process flow to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*h0VNRWJ-cP6jHgKFn-3Euw.png" /><figcaption>Fig 5. Graphql Subscription with background worker</figcaption></figure><p>Needless to say, this will require a significantly amount of work to hack the existing AsyncIterator interface. I have spent time and hacked around it, but it is not close to a production ready and stable solution.</p><h3><strong>So what now? What can we do to improve GraphQL Subscription?</strong></h3><p>If we cannot really do it like this background worker solution, at least, let’s reduce some redundant work.</p><p>You problem have already noticed, the ws server stores a list of record for every client that subscribe to a field, (e.g. userCreated field), then when the event is triggered, every record will call the associated resolve function once and send the result to client. This suggests that all these redundant calls to the resolver function (even though their parameters are different), we may still save a lot of time if we don’t do redundant work.</p><p>For example, we could have a global cache layer for the datasource when calling them in resolver.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da14b369fb0a5baa4aa4a13a7e633780/href">https://medium.com/media/da14b369fb0a5baa4aa4a13a7e633780/href</a></iframe><p>Obviously this may cause dirty data issue (data not up to date), in theory, the caching is a generic solution to the entire graphql layer, but for purpose of reduce redundant work of GraphQL subscription, we just want all the clients that are triggered by the same UserCreated event to group together and call the datasource once. It is effectively “instead of cache the value for a certail amount of time, cache it for 1 tick”.</p><p>This could be achieved by using dataloader, Instead of “cache it for 1 tick”, it collects all requests in 1 tick, and execute only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/045f378cec15a86eb89ac4ff4d635613/href">https://medium.com/media/045f378cec15a86eb89ac4ff4d635613/href</a></iframe><p>Note that this dataloader need to be globally available, and long lasting (not per request), because of this, the cache option need to be turned off, because enabling global in-memory cache is dangerous as it may cause data out of sync between different servers. (server1’s cache still has unexpired data, server2 is expired and fetching for fresh data).</p><p>If you want to know more, I suggest look back on one of my <a href="https://hansololai.medium.com/advanced-graphql-subscription-performance-85f9ab858bbe">previous post</a>.</p><h3>Summary</h3><p>In this post, I explained in detail what a regular pub/sub websocket server would look like, and compared with GraphQL subscription. I suggest that GraphQL due to it’s “execute query per client per event” nature could easily impact server performance. A large scale subscription server must be carefully designed and optimized. I gave some examples on what could be done to improve the performance of subscription.</p><p>If you have more questions, feel free to post comments, I will get back to you!</p><p>Also, follow me please!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7c103ace22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Optimize CircleCI config]]></title>
            <link>https://hansololai.medium.com/how-to-optimize-circleci-config-63a0bfa364c1?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a0bfa364c1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 04:18:49 GMT</pubDate>
            <atom:updated>2022-04-10T15:49:15.723Z</atom:updated>
            <content:encoded><![CDATA[<p>CircleCI is one of the most popular continuous integration software. It is basically a script runner that can be triggered by your github/gitlab push.</p><p>If you haven’t know about it, and you are still doing manual deploy to server, <a href="https://circleci.com/">check it out now</a>! There is a <a href="https://circleci.com/pricing/">free plan</a>! (for 6000 build minutes per month).</p><p>Once you setup the circleCI with your Github repo, whenever you push a change to the repo, circleCI will run a script that you specified to test your repo, and even deploy to cloud server.</p><h3>Standard CicleCI setup:</h3><p>A standard setup of a web app (dev/staging/prod) would generally include:</p><ol><li>A test job that runs tests, a deploy-staging job that deploy repo to a staging environment, a deploy-master job that deploy to production environment.</li><li>run test job whenever there is a push to any branch, run test and deploy jobs whenever there are commit (most likely a merge-request) to staging or master branch.</li></ol><p>3. A more complex web app, such as a mono repo, should have multiple test jobs, like test-frontend, test-backend .</p><h3>Optimize the setup</h3><p>Obviously, we want want the circleCI to be as efficient as possible, this is not to say I am cheap (I am, but that’s not the point), this is also about development productivity.</p><ol><li>Shorter turnoever. Developers will know sooner that their changes failed test.</li><li>Faster deployment. Any merge-request (push feature to master branch), is deployed faster.</li><li>Most importantly, budget. As CircleCI, (any many other services) charge by minutes, obviously less time is cheaper.</li></ol><p>There are multiple directions to approach this “do not run unnecessary tests”.</p><h4>1. Cancel previous run if a the branch is pushed a new commit.</h4><p>Luckily, CircleCI’s platform already does this. If previous job is still running when you commit a new change to the branch, the previous job is automatically canceled and a new job with the most recent commit will start.</p><h4>2. Cache test result.</h4><p>Every code commit should trigger a test run, no problem, but over the years, we have discovered, there are many non-code changes, such as .gitignore , package.json change package name, config changes that does not affect how code runs. If you put frontend and backend code together, you would want frontend changes to not run backend tests and <em>vice versa</em>. Therefore, it is a pretty important thing to add that significantly reduced our circleCI usage. (over 60%).</p><p>The idea is simple, in the circle config, we want to run tests only if a specific folder’s files are changed. CircleCI support a <strong>cache </strong>mechanism that allows you to store a folder and allow it to be loaded across all the jobs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a5e54b4f5d4b81644b0125b31812ba/href">https://medium.com/media/c5a5e54b4f5d4b81644b0125b31812ba/href</a></iframe><p>In the example code above, first, I created acode_md5.txt file by taking md5 of all files in src directory. Then, I use the restore_cache + save_cache syntax in circleCI that restores the test result in jestCov/ directory. It cache key is a long text with the checksum of the code_md5.txt file. In other words, if all the code files in src directory are unchanged, then code_md5.txt should be unchanged, the cache should be correctly found and lcov file in jestCov/ should be restored. In any case, the test run command is combined with a bash if so that only if the lcov file does not exist, will it run the test.</p><p>This combination of “build md5 of all code”, “ restore test result”, “run test only if test result is not found” allows the circleCI to skip a test if all the dependent files are not changed.</p><p>This same idea could also be applied to different kind of tests. For example, you can split up unit tests by modules, so if code in one module is modified, all other modules tests are not run.</p><h4>3. Cache package installation.</h4><p>To run tests in circleCI environment, we must include many steps to prepare for the tests. Steps like yarn install, pip install usually takes quite a long time. So obviously we would like to cache it if possible. One approach is to <strong>cache the cache</strong>. Little twisted right ? It means we want to use the CircleCI’s cache to store the yarn cache directory. Then load it before we run yarn install, this way, we don’t have to download all the packages, instead directly copy from yarn cache.</p><h3>Summary</h3><p>This post showed a way to config CircleCI to skip tests if the code is unchanged. In most cases, a feature update only modifies a couple of files, so you may save a lot of time by skipping unit tests in other modules. (Still should run integration test though).</p><p>Now if you keep tabs on new technology, you might know about this monorepo framework NX.js, which build dependency graphs of your code so that it is smart enough to know the exact tests that are affected by your changes. However, the nx.js, in my own opinion, has a lot of compatibility issues with all the existing frameworks out there, it actually create a lot of problems. So I decided to manually split up tests.</p><p>That’s it for now, I will come back soon with more tricks with CircleCI .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a0bfa364c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post Save hooks, do it right.]]></title>
            <link>https://hansololai.medium.com/post-save-hooks-do-it-right-9c5bf4afe9e7?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5bf4afe9e7</guid>
            <category><![CDATA[sidekiq]]></category>
            <category><![CDATA[background-worker]]></category>
            <category><![CDATA[web-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 04:37:52 GMT</pubDate>
            <atom:updated>2022-04-06T04:37:52.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Post save hooks is one of the common ways to connection actions to a “save” action. This kind of pattern exists in many business domains. Some examples include:</p><blockquote>Send Email after a new User is created.</blockquote><blockquote>Recalculate a user’s total_post_count when the user have created a new post.</blockquote><p>In a simple web application, developers may simply wrap the action right after the save function, or even use some dispatch mechanism to trigger actions. Some times people event right triggers into database to ensure accuracy.</p><pre>//Ruby on Rails<br>class User extends ActiveModel<br>   after_save: send_email<br>  def send_email<br>      // call email service send email notify user profile is updated.<br>  end <br>end</pre><pre>// PostgreSQL<br>create trigger after_new_post AFTER INSERT on posts for each row<br>execute procedure recalc_post_count();</pre><p>While this is a pretty good solution for many start up projects, it is not very sustainable when the server gets busy. Imagine (just an unrealistic example to make my point) a user uses an “import posts from other source” function and imported thousands of posts, do you want to trigger recalc_post_count every time a post is created ? Obviously a sensible thing to do is to wait until they are all done and recalculate.</p><p>In this posts I will talk about how we should use “triggers” correctly.</p><h4>Async trigger actions</h4><p>It is quite common to add trigger directly to the main thread code. (like the Ruby on rails example). But it has a significant flaw: the save and send_email actions are not in the same business domain, various issues could arise, for example, what if the email service is down ? In a good object oriented design, it is also not ideal to write send_email inside a User class. When there are actions that should be triggered, we should always use async triggers and delegate the job to a background worker. A full function web application should always have access to a background worker, like sidekiq(ruby), celery(python), Bull(js) .</p><p>Because of the async nature of background jobs, the job may be delayed (depend on how you manage the queue), but usually that’s ok, the triggered action are usually not exactly time sensitive.</p><h4>Debounced the triggers to avoid frequent invocation</h4><p>If we agree that the background jobs are not time sensitive, then we may also agree that a very frequent triggering of the job is also not necessary. If you work on frontend html, you might be very familiar with Debounced/Throttled.</p><p>Debounced/Throttled are <a href="https://css-tricks.com/the-difference-between-throttling-and-debouncing/">slightly different</a>, but they both are used very frequently in frontend web pages to solve one simple problem: user click a button to trigger an action too fast.</p><p>The same idea could be applied to this “triggered action”, if an update happened too frequently, then instead of triggering one job per update, it could be debounced, or throttled to trigger much less jobs.</p><h4>Jobs should be designed to be idempotent and transactional</h4><p>Background workers are different process than the main web application, the way they communicate with each other is by some broker or message service, such as redis, rabbit-mq .</p><p>This extra level of network service increases the risk of unexpected failures for background jobs. This is expected, as we already know, an async of background worker to complete some recalculation is not as stable as just inserting the code inside the main thread, but with careful designing of the jobs, the pro outweights the con significantly.</p><p>One of the key design consideration is that the job should be <a href="https://github.com/mperham/sidekiq/wiki/Best-Practices#2-make-your-job-idempotent-and-transactional">idempotent and transactional</a>. Idempotent means the job can be triggered multiple times, the result would still be correct.</p><p>A example of un-idempotent job would like as follows:</p><pre>class Post<br>after_create: increament_count_job</pre><pre>// background<br>def increament_count_job(user_id)<br>  user = User.find(user_id)<br>  user.post_count = user.post_count + 1<br>  user.save()<br>end</pre><p>The above job is very important to be triggered once per post creation, and cannot be debounced, or rerun. A good example, would be like below:</p><pre>class Post<br>after_create: recalc_count_job</pre><pre>// background<br>def recalc_count_job(user_id)<br>  user = User.find(user_id)<br>  user.post_count = user.posts.size()<br>  user.save()<br>end</pre><p>The idempotent characteristic enables a failed job to be retried constantly until successful. It is much easier to have a retriable job, than having a complex try catch to deal with failure. However, even an idempotent job may have side effects that may not work well. For example:</p><pre>def send_email_to_new_user(user_id)<br>  send_welcome_email(user_id)<br>  user.welcome_email_sent = true<br>  user.save()<br>end</pre><p>If the user.save() failed, the email has already been sent, you should not retry the job, because that would send duplicate emails. This is what transactional mean. The job, if failed in the middle then retried, should not produce duplicate side effect. The best is to make the job rollbackable, when it failed half way, a try/catch mechanism automatically rollback the current changes, like the database transactions. But usually it is not necessary, a retry of the job could overwrite the changes, you do a little extra work, (full retry, instead of recover from failed code) but that is little price to pay.</p><p>With these two important points in mind, the background jobs should be very easy to manage.</p><h4>Use multiple Queues to control the jobs</h4><p>Now you have moved all your trigger action into some background job and your website is getting popular, and application is getting more complex. You find yourself running into problems of jobs delayed too much.</p><p>Then you should consider having multiple queues to manage the jobs.</p><p>Most background worker framework, the jobs are deployed to a queue, by default it is called something general like “default”. And you can start multiple <strong>worker </strong>processes, which continuously poll from the queue, and execute the job in parallel. The framework should also let you to specify which queue(s) the worker should pick from.</p><p>As an example setup I like to use:</p><pre>Queue 1:<br>  name: fast<br>Queue 2:<br>  name: data-sync<br>Queue 3:<br>  name: slow</pre><pre>Worker 1-10: Pick job from Queue 1 only<br>Worker 11-15: Pick job from Queue 2 and Queue 1 (prefer Queue 2)<br>Worker 16-20: Pick job from Queue 3 and Queue 1 (prefer Queue 3) <br>Worker 21-25: Pick job from Queue 4 and Queue 1 (prefer Queue 4)</pre><p>Most of the quick jobs, like “send email”, “updating some other field after you save post” etc are in Queue 1. jobs like “sync financial data into local database” are in Queue 2, because they take longer time, and may fail due to third party’s api may not be stable. Queue 3 is for jobs that takes much longer time, mostly they are cron jobs that fetch data from local database and recalculate some statistics.</p><h3>Summary</h3><p>In this post, I talk about a recommended way to handle trigger actions that is associated with a data change. I recommend use background worker to handle these trigger actions because the background jobs can be <strong>debounced/throttled</strong>, and design these jobs to be, in simple words, “<strong>retry-able</strong>”. Also if application gets more complicated, consider using <strong>multiple queues</strong> to handle the jobs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5bf4afe9e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphql — Extending Graphql Server]]></title>
            <link>https://hansololai.medium.com/advanced-graphql-extending-graphql-server-2b6bf02fe1b?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b6bf02fe1b</guid>
            <category><![CDATA[envelop]]></category>
            <category><![CDATA[plugin-development]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo-server]]></category>
            <category><![CDATA[envelop-plugin]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Sat, 02 Apr 2022 17:34:57 GMT</pubDate>
            <atom:updated>2022-04-02T17:34:57.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extending Graphql — Comparison of Apollo plugin, Envelop and Graphql Middleware</h3><p>GraphQL is an awesome query language and we have been using it for many years. Over the years, we have had many needs to do some non-resolver level modifications of the server and we have discovered many strategies. This post aim to summarize some of them and discuss a good strategy.</p><p>TL; DR</p><p>Apollo Server Plugin is less powerful than Envelop, but it showed good design considerations and is more favorable.</p><h4><a href="https://github.com/maticzav/graphql-middleware">Graphql Middleware</a></h4><p>Graphql middlware is one of the first libraries that were created to modify graphql schema. This strategy, in their words, an “onion” principle, works similar to any web server middleware (expressjs middleware, Django middleware, Rails middleware), it allow users to wrap the existing resolver function with a new resolver.</p><pre>const newResolver = (oldResolver, _,arg,ctx, info){<br>   // add some code before resolve<br>   const result = await oldResolver(_,arg,ctx,info);<br>   // add code after resolve<br>   return result;<br>}</pre><p>But notice, this is a <strong>schema </strong>modification, given an old schema, developer can apply many middlewares and generate a new schema. Then use this new schema in process graphql requests.</p><h4><a href="https://www.envelop.dev/docs/plugins">Envelop Plugins</a></h4><p>Envelop Plugin an upgrade of Graphql Middleware. In a normal process, a graphql query goes through parsing, validation, execute three steps. in parsing step, the graphql query text is converted into an AST(abstract syntax tree), in validation step, the AST is then matched against the schema. This is the step where it ensures that the user query is not request fields that the schema does not have.</p><pre>// graphql query<br>query {<br>   user {<br>     id<br>     name<br>     age<br>   }<br>}<br>// schema<br>User {<br>  id: Int<br>  name: Int<br>}<br>// Validation error, &quot;age&quot; field not found in schema. </pre><p>Then inexecute step, the resolvers in schema are called accordingly to form the graphql response.</p><p>The library envelop provide ways for users to modify all three steps. It not only allows user to add preXXX and postXXX code for each step, it even allows user to completely replace the existing function in the plugin. via the setParseFn, setValidationFn, setExecuteFn function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*UrjEmQvQcN66jmPweyVFqg.png" /><figcaption>Envelop API for modify parse step</figcaption></figure><p>Similar api are also provided for validation and execute step. Besides these standard steps, the package also allows user to modify context creating (happened after validation), and onSubscribe, onSchemaChange(run code when schema change, this usually happen in federation, some times part of schema is available after server is up). onResolverCalled (works like middleware, triggered when every resolver is called). Example of wrap parse is shown below.</p><pre>// <br>const plugin = {<br>   onParse:({parseFn, setParseFn})=&gt;{<br>      const newParse = (...params)=&gt;{<br>         // add your code before parse;<br>         const result = parseFn(...params);<br>         // add your code after parse;<br>          return result;<br>      }<br>    }<br>}</pre><h4><a href="https://www.apollographql.com/docs/apollo-server/integrations/plugins">Apollo Server Plugin</a></h4><p>Apollo Server is a full featured server designed specifically for graphql, with the plugin system, users are also able to inject code in the three steps: parsing, validation, execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*qG6lX0lRxepDgZ9gw_RCJw.png" /><figcaption>Apollo server plugin lifecycle From <a href="https://www.apollographql.com/docs/apollo-server/integrations/plugins/#request-lifecycle-event-flow">https://www.apollographql.com/docs/apollo-server/integrations/plugins/#request-lifecycle-event-flow</a></figcaption></figure><p>User implement the xxxDidStart function according to the api, and it would be executed right before xxx, if the xxxDidStart returns a function, the function will be executed right after xxx.</p><p>The main difference between the apollo plugin and envelop plugins, is that Apollo plugin implementations do not affect the graphql query parsing and validation, only the willResolveField (works as the onResolverCalled in <strong>envelop</strong>) can affect the execute step. So the main reason for the plugin functions are for logging purpose. For example, you could collect request and send to newrelic, or other server monitoring server.</p><h3>Comparison of GraphQL Middleware, Envelop and Apollo Server Plugin</h3><p>Now for the good stuff, the comparison. This is a quite opinionated section, I happened to have used all three of them in production and discovered some pros and cons in these frameworks.</p><ol><li>Most people only need to inject code in resolver (change schema), in this perspective, all three libraries are able to do it well. There is little to no performance difference between these three in terms of “wrapping resolver”, it is just a difference of syntax.</li><li>Apollo server plugin takes a very restricted approach when it comes to plugin, it allows async functions to be injected, but it does not affect the main flow result. For example, in the source code below, the validationDidStart event is triggered right before validate and await to finish. Then validationDidEnd is called right after. But non of the returned result is affecting the main validate call. The dispatcher dispatch the event, all the validationDidStart function from plugins are called and collected with Promise.All . This is very restricted to the user of course, because you are not able to change the behavior of the server, but it has a great advantage.</li></ol><blockquote><strong>Each plugin are always independent of each other, and called in parallel.</strong></blockquote><p>in other words, the order of plugins does not matter. And this is important! (I will talk about it more after I talked about envelop).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*LdNaVbdJx6qaDaTXZ_MILw.png" /><figcaption>sourcecode from apollo server: invoke validation step.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*RBY9s_aBWlPHmi6nMuAEZA.png" /><figcaption>source code from apollo, dispatcher.invoke</figcaption></figure><p>3. Envelop plugin, however, is completely opposite, it gives developer so much freedom that you can basically do anything. Because it offers a setXXXFn api, so developer, if choose to, can replace the validate, parsing, execute with any function they want.</p><p>4. Wrapper style plugin is powerful, but dangerous. Because it allows plugins to depend on another. The problem with plugin dependency is that it is always assumed to be independent and the order of dependency is not like “imports” which usually can be found in compile time. It is hard to check and maintain. It is also a very common problem too, in many frameworks, Django middleware, expressjs middleware, even Ruby on rails activerecord callbacks. (the after_xxx callbacks are execute in order, so it is easy to have some dependency without knowing it, see this <a href="https://github.com/rails/rails/issues/19590">issue</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Y6IVPS8rFCi5ky5cDHYjSQ.png" /><figcaption>Django middleware dependency for cache</figcaption></figure><p>As author of plugin, one should always try to make it an independent plugin and free of side effect, but it is hard to enforce the author to comply this rule. Some may add test cases, for example, we have an integration test that shuffles the plugins and run sample queries to ensure the results are still the same.</p><p>From my years of programming, I have seen developers doing enough crazy things to know that</p><blockquote>in a team of many developers, you cannot rely on every developers to follow the style guide, you must enforce them. If you want to prevent an anti-pattern, either add lint/test check, code review yourself, or do not give them the ability to write it.</blockquote><p>The “resolver wrapper style” plugin like Graphql Middleware, onResolverCalled in Envelop, executeDidStart in Apollo Plugin is hard to avoid, because people do tend to modify the result of resolvers. But validate and parse step are pretty standard and we should avoid doing this “wrapper style” as much as we can. Which is why I, in my personal opinion, think that Apollo Server Plugins is a better design. Also, Apollo server plugin’s functions are all async, which allows user to do things like “send preparsed query to Datadog, or some other data collector”, but Envelop’s validate parse are synchronous, which focus on modify the behavior of validate and parse .</p><h3>Summary</h3><p>In this blog, I compared three ways to extend graphql server. I focused on comparison of <strong>Apollo Plugin</strong> and <strong>Envelop</strong>. I briefly explained how powerful envelop is, but lack of design choices. In my opinion, totally opinionated framework is not good, but neither is a totally non-opinionated barebone. Apollo Server Plugin made some hard choices when designing the plugin interface and in my opinion, is the right choice. So <strong>I would favor Apollo Plugins for now</strong>. It definitely has some limitations, but I trust them having no problems address these limitations in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b6bf02fe1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Webapp from Scratch Part 2 — Presentation Layer]]></title>
            <link>https://hansololai.medium.com/design-webapp-from-scratch-part-2-presentation-layer-a1e4e4826fc6?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e4e4826fc6</guid>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 04:23:47 GMT</pubDate>
            <atom:updated>2022-03-31T04:23:47.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Webapp from Scratch Part 2 — Presentation Layer</h3><p>Following <a href="https://medium.com/@hansololai/design-web-app-from-scratch-part-1-394814152b94">Part 1,</a> imagine we have a web app architecture like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*U4Sla8Q4CsKMEdfkvYwdyw.png" /><figcaption>Figure 1. Standard web application architecture.</figcaption></figure><p>And The Core is already coded up by other teams, and your job is to implement a presentation layer.</p><p>Components in this layer handles three things:</p><ol><li>validate the request parameters</li><li>Construct command to call Corefor each request from outside</li><li>Generate response appropriately from the return result from Core</li></ol><p>Each point worth a couple of blogs, but let’s just walk through them briefly, we’ll go into details later.</p><blockquote>TL; DR: scroll to the bottom</blockquote><h3>Validate Request Parameters</h3><p>The part includes Authentication of user, verify the input parameters are valid (may be even partial authorizations). The Input parameter validation is supposed to be a static checker, not business logic checker. For example, you could validate the date string is actually a date, or some int parameter is in a certain range. (If you are thinking about <a href="https://alibaba-cloud.medium.com/an-alibaba-cloud-technical-experts-insight-into-domain-driven-design-domain-primitive-c569986cebcd">Domain primitives</a> for validation, that’s great, you are ahead of me). Note that complex validation such as, “does this date match to any of my blog dates?” should not be in here. These kind of logic is business related.</p><p>This part is also good for some quick RBAC authorizations, such as does the user have the permission to access certain service. This is actually a quite controversial topic. Because I have seen designs where full RBAC authorizations are implemented in controller, so the calls to service contains no user data. This way the service layer can implement cache easily because it does not return user specific data. But on the other hand, you cannot really know what kind of data you need until you are actually in the service, so doing RBAC before you call the service is quite hard and limited. That is why I mention partial authorizations, because I do believe some level of RBAC could be implemented here and issue an early return for the benefit of performance, but investing too much effort for full authorization framework in controller is not ideal.</p><p>The validation section is preferably a static checker, with little or none database travels. Technique such as JWK authentication (avoid query the database to know the user is valid), or cache a permission hashtable for fast authorizations are very helpful.</p><h3>Construct Command to call Service</h3><p>Calling service in controller/command line client should be pretty straight forward (Unless it is cross language, and you are building rpc). You just import the service in controller and directly call it.</p><pre>import userService from &#39;services&#39;;<br>class UserController {<br>    @GET<br>    async getAll(){<br>      const users = await userService.getAll();<br>      return formatResponse(users);<br>   }<br>}</pre><p>GraphQL, however, takes quite a bit effort to make it performative. Which is one of my focuses in this series of blogs.</p><blockquote><strong>GraphQL transfers responsibility to backend</strong></blockquote><p>In the old days, we have Rest API, where we define a series of endpoints and return response using some common definition that both frontend and backend agrees.</p><pre>User {<br>  id: Int<br>  name: String<br>  friends: Int[]<br>}<br>GET /users/:id<br>GET /users/id[]  // get list of users<br>GET /users<br>POST /users<br>DELETE /users<br>PATCH /users/:id</pre><p>If the js client in browser would like more data, the frontend developer would need to write the entire data fetching logic. For example, if you need to get a user’s friends:</p><pre>1. Get user id = 1<br>2. call GET /users/id[] to get all the user&#39;s friends. </pre><p>Possibly if this person got too many friends, one GET call will time out in browser, so frontend developer may need to fetch 50 at a time.</p><pre>1. Get user id = 1<br>2. for 50 in a batch call GET /users/id[] to get all the user&#39;s friends.</pre><p>This mixture of both “business logic”(get user’s friends), and “optimization logic”, (take batch of 50 at a time) is not ideal for a frontend developer whose major job should only be dealing with GUI (considering style, match the html with designer’s handout, dealing with interactions, etc), not to optimize how to request all kinds of data. Also as the request of data become more complicated. the “optimization part” may get more tedious.</p><p>Hence the rise of GraphQL! A lot of posts have talked about GraphQL’s advantage of getting all the data in one query, so frontend developer never have to worry about these data fetching optimization again. However, the difficulty of data fetching still exists, it’s just transferred to backend developers. In a GraphQL schema shown below,</p><pre>User {<br>  id: Int,<br>  name: String,<br>  friends: User[]<br>}<br>Query {<br>   users(id: Int): User<br>}</pre><p>The “optimization logic” reside in the web server now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*-2G2PYiOQqdbZ8zNK9UfqQ.png" /><figcaption>optimization done in server</figcaption></figure><p>Now it is the backend developer’s responsibility to optimize the resolver. The difference is, in Rest API, the frontend developer work on optimizing his need, but in GraphQL, the backend developer need to optimize the resolver in a more generic way, so that it does not just behave well for one query, but badly for another.</p><h4>Path to optimization</h4><p><strong>Dataloader</strong></p><p>There are numerous tutorials about how to use dataloader for GraphQL, so I won’t talk in details about dataloaders. In general, it is just a library that can batch multiple calls for single item, into a call for multiple items.</p><pre>const loader = new DataLoader(&quot;function to handle array of ids&quot;)</pre><pre>loader.load(1)  // load(key)<br>loader.load(2)<br>loader.load(3), will be batched and calls the function that handle array of ids.</pre><p>A couple of things that should be noted:</p><ol><li>Dataloader caches the result in a key:value map in its lifetime. So<strong> it is highly discouraged to create Dataloader out of request context</strong>.<strong> It is recommended to create dataloader per request</strong>, and destroy it after request is finished. If you really want to use dataloader as a long live object, you should disable dataloader cache. Replace the cache with a expiring LRU cache is also not the solution, because you might have multiple servers, and LRU out of sync between them can cause GUI to be very inconsistent. Now naturally, you would think, “what about a centralized cache for dataloaders in different servers? like memcache”, not only that does not work with dataloader (dataloader’s accept cache.get() method must be synchronous), but also this is a bad idea, which I will explain in the <strong>Caching section</strong>.</li><li>Dataloader ideally would prefer a key that is easy to understand, both for deduplication when multiple calls of load(key) are invoked with the same key , but also for easy retrieval of the value in cache. If the key is just an id, int or string, that is great, but if the key is a complex json object, it is quite difficult to dedup. Even if you provide a cacheKeyFn to convert the key into string by stringify, you may still have to sort them. (because two equivalent json object may stringify to different string because the order of their keys are different.</li></ol><p><strong>Caching</strong></p><ol><li>Don’t use in-memory cache globally</li></ol><p>In-memory caching is the fastest cache to use, but unless it is to cache result of a <a href="https://en.wikipedia.org/wiki/Pure_function">pure function</a> or immutable data (data that does not change, in which case the getXXX function is also pure), it is discouraged to use in-memory cache in a global scale. In other words, in-memory cache should always be used in some context.</p><p>The reason is that, if a function is not pure, for example, the returned value of same input is different due to timestamp, database data update, then in-memory cache might be updated in one server, but still not updated in another server. This causes cache inconsistency. For example:</p><pre>const cache = {}<br>class User {<br>   update(id, data){<br>     const newUser = userRepo.get(id).update(data);<br>     cache[id] = newUser;<br>  }<br>}</pre><p>Whenever you update user you always update the cache with the newest user. It might work for server1, because the update request was handled by server1, but for all your other servers, 2...n their cache is not updated.</p><p>2. Use memcache with caution</p><p>The next best thing of in-memory cache, is some centralized memcache, some nice cloud servers offers very fast memcache solution. Some of them response time is just a couple of ms. However, there is a gotcha that I have seen happening many times: memcache used to store id:model . I am not saying this is wrong, but you must be cautious about this kind of caching.</p><p>For example, in the above example of “getting one user’s friends”</p><pre>// setup memcache<br>const memcache = // set up connection</pre><pre>async function getListOfUsers(ids){<br>    const uncached = [];<br>    const result = [];</pre><pre>    for(id: ids){<br>      const cachedUser = await memcache.get(id);<br>      if (cachedUser){<br>         result.push(cachedUser);<br>      }else{<br>         uncached.push(id);<br>      }<br>    }<br>    const rest = await userDb.getMany(uncached); // get list of users<br>    // add rest to result<br>    result = Arrays.concat(result, rest);<br>    return result;<br>}</pre><p>The above code is innocent enough right ? for each id, check if it exist in cache, collect the users that exist in cache, for the uncached ids, we make one database trip to get the rest, then merge the two arrays. However, in practice, this approach is<strong> much much slower than</strong> just a simple call to the database. There are two main reasons:</p><ol><li><strong>Memcache is a cloud cache. </strong>No matter how fast memcache is, it is still a network request, it is a couple milliseconds at least.</li><li><strong>Simple indexed db retrieval is limited by network latency. </strong>database retrievals with multiple ids(indexed) is usually very fast (with reasonable size 100 or so), fast enough to ignore the execution time between getOne and getMany , the bottleneck of the request, guess what, is still the latency.</li></ol><p>So if you compare the above approach, which may need as many as N trips to memcache, vs a simple database.getMany() , which is 1 network trip, in most cases, the simple solution wins in performance.</p><p>So as it concludes my point,</p><p><strong>do not use memcache to small tiny data</strong></p><p>It is useful, but you must be cautious.</p><h3>Summary</h3><p>In this post, I have talked about what the <strong>Presentation Layer</strong> should be, and talked about GraphQL, (as one of the presentation layer component). I explained</p><ol><li>GraphQL is not magic, it transit the responsibility from frontend to backend.</li><li>Two ways to optimize GraphQL: dataloader and caching and some notable points that should be considered.</li></ol><p>In next post, I will explain in detail with some demo code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e4e4826fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Web app from Scratch Part 1]]></title>
            <link>https://hansololai.medium.com/design-web-app-from-scratch-part-1-394814152b94?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/394814152b94</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[web-architecture]]></category>
            <category><![CDATA[web-server]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 17:39:04 GMT</pubDate>
            <atom:updated>2022-04-10T23:29:31.927Z</atom:updated>
            <content:encoded><![CDATA[<p>Start a webapp from scratch might be overwhelming, even with a lot of SaaS, PaaS that helps you deploying these apps, writing the app itself from scratch is still difficult.</p><p>In Part 1, I want to emphasize on one single mistake that I see happening in many web applications. That is:</p><p><strong>Write your business logic in the Core</strong></p><p>Let me explain. Imagine you have a pretty standard design of an web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*U4Sla8Q4CsKMEdfkvYwdyw.png" /><figcaption>Figure 1. Standard web application architecture.</figcaption></figure><p>Note this is not the three-tier design. It would fit into the “Your application” component in a three-tier design of a web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*aU_Ev13DotTYjDBEehCXiQ.png" /><figcaption>Three-Tier architecture. Source: <a href="https://www.logianalytics.com/5-benefits-3-tier-architecture/">https://www.logianalytics.com/5-benefits-3-tier-architecture/</a></figcaption></figure><p>This architecture design is pretty standard, a presentation layer(GraphQL, Rest, commandline) calls some functions in the core (read or write), and the core, through ReadService or WriteService, fetch data or modify data in storage and return to the presentation layer. There are many variations of this design, but we won’t get into details for now.</p><p>Most of the time, when you need to start a web app, it is a much simplified version. For example, you might not need to support commandline, the data requests are very straight forward that you might want to skip writing a service file. Which leads to the design in Figure 2. This is quite common when all you need is a CRUD api to access the database, the read and write are very straight forward and can be generated. Many web frameworks support this kind of style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*r-JwXr4-jz5Grtm88Ve67w.png" /><figcaption>Figure 2. No service</figcaption></figure><p>For example, RoR(Ruby on Rails) allow direct access to Storage layer(aka ActiveRecords) in Controller. (see their demo code in Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*DHxU03GWHYsw1BpX7tfssg.png" /><figcaption>Fig 3. RoR demo code: Model access in controller</figcaption></figure><p>Or some one-click GraphQL framework like Hasura, PostGraphile.</p><h4>Don’t put business logic in controller, put them in CORE.</h4><p>But sooner or later, you will need to extend the simple web app with extra functionality and lazy developers may choose to write business logic directly in controller files and end up with bloated controllers. And it become much harder to add additional component: such as 1) adding background worker to execute Tasks that need to reuse controller code, or 2) add another presentation mechanism (GraphQL, RPC etc).</p><p>There is a common misunderstanding of MVC(model view controller) framework, that is, people think Models are the models created in ORM that is 1:1 with database tables. With this kind of thinking in mind, obviously the only place to write business logic is the controller. But Models are not restricted to just DAO(data access objects), in fact, models to quote wiki:</p><blockquote>The central component of the pattern. It is the application’s dynamic data structure, independent of the user interface. It directly manages the data, logic and rules of the application.</blockquote><p>The controller has a very simple purpose, accept inputs and convert to command for Models and render View. To put into the diagram above, the Models (in MVC framework) is the entire Core component. (I will cover more about how to design core in later posts). If you ever foresee your application grows into medium size and is not just a simple CRUD retriever, you should always enforce this rule to not let controller have direct access to storage layer. Some language linter even provide the ability to restrict imports so developer cannot import user model in userController file. <a href="https://pypi.org/project/pylint-restricted-imports/">Pylint</a>, <a href="https://eslint.org/docs/rules/no-restricted-imports">eslint</a> to name a few.</p><h4><strong>Don’t put business logic in database neither.</strong></h4><p>That is not very obvious to developers, and is very easily missed.</p><p>Database like PostgreSQL provide pg_functions, pg_views, pg_triggers that enables developer to write some business logic as SQL. But it is not recommended, for two reasons:</p><ol><li>Database cost more. When your server attracts more traffic, it is inevitable to scale your server, either by vertical scaling(increase the powerfulness of existing machine), or horizontal scaling(get more machines). Vertical scaling is almost always more expensive than horizontal scaling. For web servers, horizontal scaling is usually a simple thing to do, add a load balancer at the front and increase the number of machines, many existing cloud services even provide auto scaling for web apps. (<a href="https://www.cloudsavvyit.com/5090/how-to-set-up-auto-scaling-on-google-cloud-platform/">Google Cloud</a>, <a href="https://aws.amazon.com/autoscaling/">Aws</a>). But it is much much harder to horizontal scale your database. Usually the best option for cloud hosted database is just to put more money and get a more powerful database server. So if you consistently put unnecessary work in database, it will be quite awkward when database run out of power.</li><li>SQL is hard to read and manage when there are a lot of it. I have seem people write all the business logic in pg_functions. They are stored in .sql file for easier reading. pg_functions depend on others, and when modifying a function, all pg_functions that depend the said function must be dropped, and recreated after the new version of the function is created. This become a nightmare when you have over like a hundred functions in the system. Not only that, because of the strong dependency, anytime you modify a table (e.g. remove a column), there won’t be any checks to tell you that some function won’t work.</li></ol><p>Because of this, for a full function web application, it is recommended to write data retrieving logic and data modification triggers in web server instead of in the database.</p><p>For example, we used to have a trigger on every blog creation to add some data to a summary statistics. We wrote that in a pg_trigger and thinking this would guarantee the data is correct, because there is no way a blog is created, but the summary statistic failed to write. We are correct for the data guarantee and it worked for a while, until we developed a bulk import functionality. It took forever to import a couple thousands blogs and we finally figured out it was because the trigger was happening constantly. Eventually we moved the triggering logic to server, and for bulk updates, only write the summary statistic once at the end. It is much more elegant this way, not only it is easier to manage, (reading OO code is indeed easier than look for pg_function/pg_trigger in database), but also we have control of when it should trigger.</p><h3>Summary</h3><p>This blog explained a standard architecture design of a general web application and made one point:</p><blockquote>Write your business logic in core, not in controller, not in database.</blockquote><p>In next series of blogs, I will go into details about each of these components.</p><p><a href="https://hansololai.medium.com/design-webapp-from-scratch-part-2-presentation-layer-a1e4e4826fc6">Part 2 is here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394814152b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgraphile in Production: What to do and not do.]]></title>
            <link>https://hansololai.medium.com/postgraphile-in-production-what-to-do-and-not-do-1187404a353a?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/1187404a353a</guid>
            <category><![CDATA[postgraphile]]></category>
            <category><![CDATA[crud-mutation]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Sat, 26 Mar 2022 01:30:20 GMT</pubDate>
            <atom:updated>2022-03-26T01:30:20.416Z</atom:updated>
            <content:encoded><![CDATA[<p>Postgraphile is a very performative one click Graphql server. We tried it three years ago and really liked it and have been using it ever since. However, as our business grows, we came across a number of pain points that makes our api server unbearable. A number of design flaws were revealed as the data size grows. I compiled a list of things that we should have enforced at the beginning before it is too hard to refactor.</p><h3>Don’ts</h3><h4>Don’t use connection-filter plugins without understanding the consequence.</h4><p>There are several plugins that makes front end developer’s life very easy, such as <a href="https://github.com/graphile-contrib/postgraphile-plugin-connection-filter">connection-filter</a>. As a backend developer, it was very tempting to just enable this plugin so that front end developer don’t have to ask backend to create new api or resolvers, they could just use some filter and get the data. However, as the nature of any application is to be backward compatible, once you enable this plugin, it is almost impossible to disable it in the future. Things soon get out of hand, some intern or junior developer end up injecting some crazy filters that worked ok with less data, but two years later, exploded on our face. It took quite a while to track that down due to a bunch of mixed issues which I will cover later. Instead, try to manually use <a href="https://www.graphile.org/postgraphile/make-add-pg-table-condition-plugin/">makeAddPgTableConditionPlugin</a>, it takes some time at beginning, but trust me it will worth it. It makes refactoring much easier.</p><p>Of course, it is a very useful plugin and I am definitely not saying don’t use it, I just mean when you do use it, really make sure your team member understands the limitation of the plugin and use e2e test to ensure it does not break.</p><h4>Don’t make expensive computed_columns</h4><p>Postgraphile makes it so easy to add new fields to existing models, you just have to make a pg function named a specific way([model]_[field_name]), it will appear in [model] as a new field [field_name]. But it is very crucial to make it not expensive. Adding aggregate functions and such almost inevitably will have a scale issue. It might be ok now, but once data size grows, you get paged at night.</p><p>Also, when you added an computed_column, at some point later project manager may ask you if they can fetch data with filters on this field, or order by this field, then you added a <a href="https://www.graphile.org/postgraphile/make-add-pg-table-order-by-plugin/">makeAddPgTableOrderByPlugin</a> and because this pg function is calculated for every record in the table in order to do the OrderBy, it may very lightly be slower and slower. My company’s table grows exponentially in the past 3 years and we started to notice a lot of these computed_columns taking too much resources and even break the entire database.</p><h4>Don’t make expensive views</h4><p>I know I said “ pg function is calculated for every row” before, but postgresql may be smart enough to inline the function SQL into the main SQL and do some rearranging and speed up the process dramatically. Same kind of optimization also applies to PgViews, sometimes it is applied to views better than pg functions. Obviously with the power of PgViews, and smartTag foreignKeys, it is very easy to extend a model with more fields. For example</p><pre>type User {<br>id Int<br>Name String<br>}</pre><pre># This is a view with a fake foreign key comment on the table so     # these two models are associated.<br>type UserInfo {<br>userId Int  <br>postCount Int<br>avgReview Float</pre><pre>}</pre><p>But it is also very important to now keep in mind if scaling issue of views. We had a tree structure models in our database, a service that go through a number of changes (happened in any time) and end up with a final price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*g6rF085Sp1bsziPoCeJpdQ.png" /></figure><p>To answer question like “What was the price of all service on 2021–02–01”, or “What was the price of all services two month later”, we used postgres recursive view to calculate all the service’s price at any point in time. Then we use a smartTag foreignKey to associate the view with service table and done, we get the data. However, a year later our service table and also the changes table size increased dramatically and this view become very expensive, so we made it into a materialized view and refresh every hour. And here comes to my third point:</p><h4>Don’t make extremely large materialized views</h4><p>The recursive view is so much larger than the service table and changes table combined, each time it refreshes it takes so much memory and almost completely freeze the database for a couple of minutes or even break postgres and force it into restart. This become unbearable very quickly, because when postgres is down, everything is down.</p><p>We once were asked to build a front end that shows all the financial records of each customer and we decided to put that into a materialized view and refresh every hour. Because the view is built from many tables, (invoices, bills, services, users, invoices from third party etc), and so complex (over 500 lines of SQL) the refreshing is so expensive that when it reaches 10 million records it’s just not possible to do anything else for about 10 minutes.</p><h4>Summary of Don’ts</h4><p>Basically all of these don’ts here are really pointing to one thing: <strong>Don’t make read request taking too long. </strong>This is obvious at first, but very easily forgot when developers are rushed to deadline and chose the easy route. (For a better alternative, see the Dos list below). Even if you do create view/pg_functions, really think about scalability, stress test these views before putting them to production.</p><p>So the lessen learned here is:</p><ol><li>Always think about scalability when building pg_function, pg_views and materialized views.</li><li>Restrict on what client can filter/order so that it will be easier to optimize in the future instead of giving them all the freedom.</li></ol><h3>Dos</h3><h4>Read official doc</h4><p><a href="https://www.graphile.org/postgraphile/performance/#how-can-i-improve-performance-of-my-postgraphile-api">improve performance</a> and <a href="https://www.graphile.org/postgraphile/best-practices/">best practice,</a> they are quite important and extremely helpful.</p><h4>Take the Time to build Triggers correctly</h4><p>This is a very broad topic, let me walk through it. Usually as the application starts to grow, the logic of fetching some GraphQL queries might become more complex, client would request for some very specific features that cannot be easily retrieved by search by ID. Let’s say you have a blog website, and you are building an admin panel. A starting GraphQL might support a field like getPosts . But soon, there may be request for feature like “give me list of posts that are from authors who have received at least 10 five stars last week”. There are two ways to approach it:</p><ol><li><strong>Option 1: Spend more time in Read: </strong>Building a complex SQL to retrieve it would be easy strategy. But there is a significant issue of this: As the data grows, the complex SQL takes longer and longer to execute, end up causing this GraphQL field too slow to complete.</li><li><strong>Option 2: Spend more time in Write:</strong> A better alternative, in this example, would be to create a column called “have_ten_stars_last_week” in author table and build triggers that update this value on every times an author is given a star. This way the read query is much faster and scalable. We just need to make sure the field is always up to date.</li></ol><p>Compare to option 1, option 2 is much more complex to implement. Assume the trigger is fired on mutation, certain framework needs to be build on it to ensure the trigger fires correctly and consistently. For example, a common way to setup a trigger is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10d44891629ca7f8464c14b976979eef/href">https://medium.com/media/10d44891629ca7f8464c14b976979eef/href</a></iframe><p>This certainly works, but if more mutations for user is added, then you have to put the trigger everywhere and it is very easy to forget. So a slightly better way is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58146db45749fa645cbe4840c6c7343d/href">https://medium.com/media/58146db45749fa645cbe4840c6c7343d/href</a></iframe><p>Trigger should also be deferred when bulk updating. Sometimes, to ensure mutation resolves asap, the trigger action is put into background worker so that it does not block the main thread, then there will also need some retry mechanism to ensure the trigger action must complete, so that the column value is up to date. If we really wanna do it right, this might expand to a pub/sub framework and with Domain Driven Design to establish a full framework, but that is out of scope of this blog.</p><p>The key here, is that when facing a feature request that requires the developer to pick between these two options, always try to use <strong>option 2</strong> if possible. This slows down the initial develop time, but it is much more sustainable and scalable.</p><p><strong>In PostgreSQL term, try to not use view which essentially adds time in Reading, but instead build columns to store good intermediate values to speed up the read query.</strong></p><h4>Write your own mutations soon</h4><p>This is a quite opinionated point. PostGraphile can get you pretty far as a one click solution, but it has its limitations. In my web applications that I have encountered, there exists at least some models that fit the CRUD operation and would benefit with these generated query and mutation fields. When the web application is simple, a lot of bad habits are ok. For example, people even tend to get a lot of data and calculate summary stats in front end. Which would be a very bad idea when the data grows. As the application grows, at least three things could happen:</p><ol><li>Generic Create mutation is no longer feasible with large models, or tables that has been <a href="https://towardsdatascience.com/database-terminologies-partitioning-f91683901716">vertically partitioned</a>. Also there is also a suggestion about design to avoid <a href="https://xuorig.medium.com/graphql-mutation-design-anemic-mutations-dd107ba70496">anemic mutations</a>, even <a href="https://martinfowler.com/bliki/AnemicDomainModel.html">objections of entire anemic model design with pure CRUD</a>, which I feel a bit too strong, but it does make sense to some degree. When these things happen, the developer will need to create extra mutations that mutate specific data field and/or calculate stats in a “post update” trigger etc.</li><li>Business Logic(BL) grows and the dependency of functions become so tangled that it is almost impossible to manage with pg_functions like PostGraphile suggested. One example is that we used pg_functions to trigger for some model creation, but later we added csv import ability, and because of the pg_function was triggered for each creation, it significantly slow down the database, we have to figure out a way to defer the trigger when bulk updating. This urge the developer to find alternative way to implement the mutations, even if they keep the Generic Create/Update/Delete format, they still need to implement the core in a object oriented fashion, with ORM and such.</li><li>Data size also grows as the web app evolve. Many times, a front end (client) feature requires some “calculate stats” from backend (from something simple as blog count , to something complicated like user avg blog view time per month . In which case, the developer is required to face the two options that I laid out previously: 1) Write a view so it spends more time in read, or 2) write some trigger inside mutations so it spends more time in write. As data size grows, option (1) is almost never a good idea with the data size is large, and option (2) requires the developer to start inserting code into the mutations generated by PostGraphile.</li></ol><p>Developer is likely to meet at least one of these above scenarios in a medium/large size web application and is forced to modify the generated mutations. I would highly recommend that when this happens, starting adapting to a architecture design to reimplement these mutations. (The generated mutations are just generic crud creates, it won’t be that hard to reimplement them with any ORM). Something like a DDD(Domain Drive Design) would be a great pattern to start.</p><h3>Summary</h3><p>In summary, because most web application’s read:write ratio is much much higher than 10:1, it is always a good idea to spend a bit more time in write request than spend time in read.</p><ol><li>Be very careful in creating views, just complex SQL to retrieve data to return to user.</li><li>Try to use a pub/sub framework to handle data dependencies. (Blog creation event-&gt; triggers-&gt;recalculate blog count).</li><li>Start thinking about architecture style and design pattern about all the state changes and write your own mutations early.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1187404a353a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphql — Subscription Performance]]></title>
            <link>https://hansololai.medium.com/advanced-graphql-subscription-performance-85f9ab858bbe?source=rss-895461d99744------2</link>
            <guid isPermaLink="false">https://medium.com/p/85f9ab858bbe</guid>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[postgraphile]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Han]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 20:55:53 GMT</pubDate>
            <atom:updated>2022-03-19T22:18:20.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Graphql — Subscription Performance</h3><h3>Problem Statement</h3><p><strong>For every broadcast, Subscription Query is executed once per each client. A large server performance would be dramatically impacted by this.</strong></p><p>Graphql Subscriptions works as a listener to wait on server to push data instead of periodically polling the server. Besides Graphql subscriptions, there are many other existing solutions that can “listen” to server. Old fashioned websocket, ActionCable (Ruby on Rails), etc. One of the biggest difference between Graphql Subscription and others is that Graphql subscription subscript be one event, but the the payload can vary for each client. For example, image a subscription definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/250a589194503cb80633da7233dcc3a2/href">https://medium.com/media/250a589194503cb80633da7233dcc3a2/href</a></iframe><p>resolvers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ac09aaf3836bb2b24cb2080426454a6/href">https://medium.com/media/0ac09aaf3836bb2b24cb2080426454a6/href</a></iframe><p>Each client could subscribe to a subset of these fields and nested fields. Unlike regular pubsub + websocket framework, where the all clients receive the same broadcast message in a channel, in Graphql subscription, each client needs to call resolve to refetch the exact data when the broadcast happened. (see &quot;Execute Subscription Query&quot; below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*EWHiwFxARJKjrkZV" /></figure><p>(credit: <a href="https://dgraph.io/blog/post/how-does-graphql-subscription/">https://dgraph.io/blog/post/how-does-graphql-subscription/</a>).</p><p>This immediately brings up a problem, for each broadcast, the resolve function is called N times, where N is the number of subscribed client. This has a significant impact as the number of subscription client increases.</p><h3>Solution 1. Dataloader</h3><p>Now, if you use some kind of dataloader mechanism that is globally available, then this may not be a big problem. Because even though the resolver is called N times, they maybe merged in one single dataloader and endup with only 1 database visit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f7bb95547fde141643b07195cd9ffa9/href">https://medium.com/media/4f7bb95547fde141643b07195cd9ffa9/href</a></iframe><h3>Solution 2. Prisma</h3><p>Or if you use prisma client, where prisma is globally availabe, and you programed the resolve function carefully, this problem may also go away.</p><h3>More Problem: What if you use PostGraphile</h3><p>One problem I have ran into in particular, is PostGraphile’s subscription. If you don’t know about it yet, check it out <a href="https://www.graphile.org/postgraphile/">here</a>. Basically this library generate the a graphql schema from a postgreSQL schema, it use the index/foreign key to create assications, also it uses a “look ahead” to convert a large GraphQL query into a complex SQL query and run it once to retrieve all the data. It can also be directly invoked as a server with jwt, rbac etc. Because of this feature, with PostGraphile, you don’t need to manually setup prisma client, datasources, or any kind of ORM for the resolvers. PostGraphile’s subscription cleverly uses Postgres’s Pubsub (so you don’t need to run a redis) as the broker and uses the query function pg_notify as trigger to trigger subscriptions. see more information <a href="https://www.graphile.org/postgraphile/subscriptions/">here</a>.</p><p>One example of how you can set up subscription with PostGraphile is like following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/254ed92c3019d1aafd4974e1708da082/href">https://medium.com/media/254ed92c3019d1aafd4974e1708da082/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f506b6c8e8aa10756f0d8bce828d0f22/href">https://medium.com/media/f506b6c8e8aa10756f0d8bce828d0f22/href</a></iframe><p>The selectGraphQLResultFromTable embed the &quot;look ahead&quot; technique and construct a complex sql to retrieve the data. If a client subscribe to server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/913ee7777f5814f8fa526362f32cf92f/href">https://medium.com/media/913ee7777f5814f8fa526362f32cf92f/href</a></iframe><p>Inside the seleceGraphQLResultFromTable it would construct an SQL like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0f65a5167ca324a1c36b4c5474363e/href">https://medium.com/media/0b0f65a5167ca324a1c36b4c5474363e/href</a></iframe><p>The exact query will involve some alias and cte, but you get the idea. However, this look ahead helps to retrieve data with 1 single query per client, but we still cannot resolve the problem that the resolver is called once for each client. So we still need N database visit per broadcast.</p><h3>Solution for PostGraphile subscription.</h3><p>The solution for this problem is to not use the dataloader “vertically”. Let me explain. DataLoader is used to batch request to a single request, and split up the result for each individual request. Like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e50113475358ab970b4b566684eb82b9/href">https://medium.com/media/e50113475358ab970b4b566684eb82b9/href</a></iframe><p>Imagine this is a “horizontal way of batching”, there is also a “vertical” batching. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb7a1294948fbbbb251c330bfeed9492/href">https://medium.com/media/cb7a1294948fbbbb251c330bfeed9492/href</a></iframe><p>In Graphql Document, the “fields” are stored in the info(4th parameter when calling resolver), access by info.fieldNodes[0] so we in pseudocode, we should do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f76fa45647a3977e2d930399b90a79/href">https://medium.com/media/87f76fa45647a3977e2d930399b90a79/href</a></iframe><p>The merge function is a recursive function that just manually merge all the selectionSet in a graphql Document. I wrote one myself and it works pretty well, but not guarantee to be bug free.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ee9f72cc6b1b1c3c688533d7b9adf84/href">https://medium.com/media/9ee9f72cc6b1b1c3c688533d7b9adf84/href</a></iframe><p>Now let’s talk about the magicResolve. it is pretty hard to figure out how PostGraphile does the look up or find a utility existing function to match our need. The exposed selectGraphQLResultFromTable hides all the secrets from the user. So instead of figuring all these out, I uses delegateToSchema from @graphql-tools/delegate, I basically construct a graphql query like below and execute the query with the schema.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd8d7e8058b4410dbf4d89368e3de860/href">https://medium.com/media/dd8d7e8058b4410dbf4d89368e3de860/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c450b9e84cfc50434a26dba36df5fe07/href">https://medium.com/media/c450b9e84cfc50434a26dba36df5fe07/href</a></iframe><p>In practise, there are a lot of details to sort out, for example, where do these context, schema come from ? From our experiment, the PostGraphile context for query only needs a pgClient to function correctly, so we could just simply construct a context inside the dataloader. schema should be the same for all queries, so we could set the schema when we create these dataloaders. Or we just pick schema from any info.</p><p>For a full repo to demostrate this, check out this <a href="https://github.com/hansololai/apollo-postgraphile-subscription-demo">repo</a></p><p><em>Originally published at </em><a href="https://gist.github.com/869da382af7850e1ecbc96adef56a462"><em>http://github.com</em></a><em>.</em>Problem Statement</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85f9ab858bbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>