<?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 Hung Dinh on Medium]]></title>
        <description><![CDATA[Stories by Hung Dinh on Medium]]></description>
        <link>https://medium.com/@hungdv136?source=rss-c23220505de6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZYm2a5mwlnwA7OCkl7pq7w.jpeg</url>
            <title>Stories by Hung Dinh on Medium</title>
            <link>https://medium.com/@hungdv136?source=rss-c23220505de6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:38:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hungdv136/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to build a scalable and operational promotion system]]></title>
            <link>https://medium.com/@hungdv136/how-to-build-a-scalable-and-operational-promotion-system-dce6170ee4a0?source=rss-c23220505de6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce6170ee4a0</guid>
            <category><![CDATA[promotion]]></category>
            <category><![CDATA[hot-deal]]></category>
            <dc:creator><![CDATA[Hung Dinh]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 01:46:39 GMT</pubDate>
            <atom:updated>2023-09-29T01:46:39.539Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I introduce how to build a scalable and operational promotion system that allows marketing team to run promotion campaigns with complex qualification and audience targeting rules</p><h3>What is promotion?</h3><p>Promotion is a marketing tool, used as a strategy to communicate between the sellers and buyers. Through this, the seller tries to influence and convince the buyers to buy their products or services</p><p>Some methods of this procedure contain an offer, coupon discounts, free sample distribution, trial offer, buy two items in the price of one, contest, festival discounts, etc. The promotion of a product is important to help companies improve their sales because customers reaction towards discounts and offers are impulsive. In other words, promotion is a marketing tool that involves enlightening the customers about the goods and services offered by an organization — Source <a href="https://byjus.com/commerce/what-is-promotion/">Byjus</a></p><h3>What are core domains (DDD)?</h3><p>This section describes core business domains in a promotion platform</p><ul><li><strong>Campaign</strong>: Marketing team often runs a promotion program as a campaign which manages advertising messages, budgets, validity time and benefits for targeted customers</li><li><strong>Offer</strong>: Each campaign offers some benefits to users, can named it as offers which manage term conditions, discount value, … For example: <strong>Discount 20% if buy 2 items</strong></li><li><strong>Rule</strong>: Each offer has its own terms and conditions. In the other words, these are qualification rules, for example: <strong>voucher can only be used if an user purchases coffee at Highland in a business day</strong>. There are 3 conditions for this offer: <strong>1)</strong> only apply for buying coffee, <strong>2)</strong> at Highland and <strong>3)</strong> Mon-Fri</li><li><strong>Effect</strong>: How offer affects to an order, how user benefits from that offer. For example: Discount 50% in total bill or get a free item</li><li><strong>Customer Segmentation/Audience Targeting</strong>: This is to categorize customers into different groups and run different campaigns for each group, so that can offer right things to right customers with reasonable budgets.</li></ul><p>Campaign and offer are just metadata stored in database, its properties are depended in business requirement, so I won’t focus on describing these concepts in this post. Instead, I will focus on diving deep into rules and effects</p><p>The effects and rules requires input data and condition/expression to get the result. For example: “<strong>Discount 20% on total bill amount</strong>” is equivalent to <strong>effect = order.total_amount * 20 / 100</strong>. In this example, <strong>order.total_amount</strong> is the input data and “<strong>order.total_amount * 20 / 100</strong>” is the condition/expression/rule. The following sections describe what data and conditions are</p><h3>What kind of data can be used with qualification rules?</h3><p>There are three kind of data that can be used to check whether that user is qualified for an offer. Each category consists wide-range dataset that depends on the business use case of the system. The below are just example dataset for each category</p><p><strong>Contextual Data</strong>: Data that associates with a specific order</p><ul><li>Merchant Information: Where order is purchased</li><li>Payment Method: Cash, eWallet</li><li>Order Detail: Total amount, order items</li><li>User input parameters (referral code, promotion code)</li></ul><p><strong>User Profiles</strong></p><ul><li>User information (age, gender, …)</li><li>Segment (infrequent user, frequent, tech savvy, …)</li><li>Loyalty: Points, Tier</li></ul><p><strong>User transaction histories</strong>: This is transaction data of users. For example: users get 50K if they spent 1M+ VND in this month</p><ul><li>Transaction histories</li><li>Issued voucher histories</li></ul><p>Contextual data is attached along with the request, so there is no scalability issue with this kind of data, but user profile and transaction histories needs to be retrieved from database or might need to be accumulated from a large number of historical records. How to aggregate this data significantly impacts to performance and scalability</p><h3>Functional requirements</h3><p>We only focus on the following business requirements</p><ul><li>Ability to return a list of eligible campaigns for an user</li><li>Ability to return a list of eligible offers by validating user profile with rules</li><li>Vouchers can be issued after an user completes an action</li><li>Ability to operate campaigns, offers and rules on a web portal</li></ul><h3>Non-functional requirements</h3><ul><li>Response time: P99 &lt; 50ms</li><li>Throughput: 3–4K TPS</li><li>Monthly Active Users: 5–8 Millions</li></ul><h3>High Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*EgYefSHjMn4K9OABjMDr0g.png" /><figcaption>High Level Design — Promotion Platform</figcaption></figure><h3><strong>Rules and Effects</strong></h3><p>Grule or Rego can be used as a rule engine. It consists a series of binary expression likes this</p><pre>user_profile.tier == &#39;vip&#39; &amp;&amp; <br>order.total_amount &gt; 30000 &amp;&amp; <br>contain(order.items, &#39;sku_id&#39;, &#39;milk001&#39;)</pre><p>I will describe how to build this rule from web portal in a later section</p><h3>Data Aggregation</h3><p>Instead of aggregating data on-fly from many distributed databases and sources, required data will be preprocessed, accumulated and centralized into a single database (MongoDB or MySQL), it can be accessed by user id and data type as a composite key. This approach not only improves performance, but also decouples data aggregation component with other services, doesn’t need to scale other services for promotion use case</p><p>Kafka is used as data stream, each kind of data will be streamed in a different topic, a data pipeline will aggregate and persist data into database. If a new data is required, a new pipeline will be develop to process that data. Sharding or partition can be applied based on amount of data</p><p>We can extract required data types that are used in rules to only fetch necessary data to reduce transferred data</p><p>We only load data once per request and data is for a specific user, so caching this data does not improve performance since hit rate will be low</p><h3><strong>Rule Execution</strong></h3><p>It requires to scan all campaigns and offers to verify whether an user is qualified for these campaigns/offers, we can find a strategy to scan partial but it is headache to find a suitable strategy that scales well</p><p>Given that the number of campaigns, offers and rules is not too large, maximum can be few to ten thousands active campaigns and offers, so we can cache the entire active campaigns and offers along with its rules in local memory (RAM of API server, not centralized cache like Redis)</p><p>However, if a campaign or an offer is updated, cache will be stale. To tackle this problem, an event will be published to a Kafka topic whenever campaign/offer (different topic for each data) is updated. Each server instance consumes to these topics independently (different consumer group using node/host id) to update its cache by object id. With this approach, cache will be updated nearly realtime within few milliseconds. Note that we use Kafka to guarantee cache will be updated in the same order events were fired, for example it will be a problem if the following events are processed with wrong order: activate and deactivate</p><p>In short, campaigns and offers along with rules are loaded and executed in local memory, it is really fast. Data is preprocessed asynchronously and is read-only, so it is easy to scale</p><h3>How to build Rule Builder</h3><p>As campaigns and offers are changed frequently, we should build a web app for marketing team to operate promotion platform. The most challenge problem is to build a flexible but easy to use UI/UX for rule builder because it is used by non tech users. Thanks to <a href="https://react-querybuilder.js.org/">react query builder</a> we can build Rule Builder as below screenshot with a little efforts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*csQRcvoGPoXyd0QvfWgbQQ.png" /><figcaption>Rule Builder</figcaption></figure><p>Each expression consists three parts: field, operator and value (can be another field with the same data type)</p><ul><li><strong>Field</strong>: A list of fields from user profiles, contextual data and aggregation data, search by field name can be a helpful feature. We should build data dictionaries like this: field name, description and data type. For example:</li></ul><pre>{<br><br> &quot;fields&quot;: [{<br>     &quot;name&quot;: &quot;user_profile.tier&quot;,<br>     &quot;description&quot;: &quot;User Loyalty Tier&quot;,<br>     &quot;data_type&quot;: &quot;string&quot;   <br> },<br> {<br>     &quot;name&quot;: &quot;store.city&quot;,<br>     &quot;description&quot;: &quot;Store&#39;s province&quot;,<br>     &quot;data_type&quot;: &quot;string&quot; ,<br>     &quot;metadata&quot;: &quot;PROVINCES&quot;<br> },<br> {<br>     &quot;name&quot;: &quot;order.total_amount&quot;,<br>     &quot;description&quot;: &quot;Order total amount&quot;,<br>     &quot;data_type&quot;: &quot;float&quot;   <br> }]<br>} </pre><ul><li><strong>Operator</strong>: Based on selected data type, query builder will load appropriate operators such as: Equal, Greater, LessThan, Contain, StartWith, EndWith, …</li><li><strong>Value</strong>: This can be text box, date time picker, dropdown (query builder based on metadata field to load a list items from backend), or even another field</li></ul><p>ReactQueryBuilder allows us to configure translation expression for each rule (Luckily, we mostly use default translation with some minor customizations), then it automatically generates a combined expression like this and will be submitted to backend</p><pre>user_profile.tier == &#39;vip&#39; &amp;&amp;<br>order.total_amount &gt; 30000 &amp;&amp; <br>contain(order.items, &#39;sku_id&#39;, &#39;milk001&#39;)</pre><p>These rules are parsed into binary expressions and executed in memory, so don’t worry about SQL injection</p><p>If new data fields are required, then only need to update data dictionary and almost everything will work out of the box</p><h3>How about defining effects?</h3><p>The effects are also rules as the below example</p><pre># Discount 20% if total amount &gt; 20000, cap 10K - 30K<br>if order.order.total_amount &gt; 200000 <br>   return max(min(order.total_amount * 20 / 100, 10000), 30000)<br># discount 10K <br>else <br>  return 10000</pre><p>Instead of using a complex rule builder, we should explicitly implement a customized UI for each effect since there are only few formulas as long as the codebase allows us to customize/plugin UI for new formula quickly. Because, as we mentioned, effects are used to calculate final total order amount, new vouchers, free items, and/or earning points. This approach provides a better UX with informative instructions as the following screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWUFUAT5dCFyLI1Qm52Xjg.png" /><figcaption>Percent with cap</figcaption></figure><p>The generated expression for the preceding effect is: “order.total_amount = order.total_amount — max(min(order.total_amount * 5 / 100, 10000), 50000)”. The output for below effect will be “order.total_amount = order.total_amount — 10000”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTC4MyqHmI0ZANNLb2QLIA.png" /><figcaption>Fixed Value Discount</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IasKIauNH-agfy1gvcD1Q.png" /><figcaption>Flat Value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPwDOjgMRHZaDz5lhXFM5Q.png" /><figcaption>Earn Point</figcaption></figure><p>Note that on top of each effect, we might have condition as the example at the beginning of this section. So the same query builder component is used build that condition. The decision tree is used at the backend side, so it can support very complex rules, so just focus on UX to define effects</p><h3>How operation team test?</h3><p>They can add a rule/condition to check by user id or a specific group of users before publishing to all users. This also allows them to do A/B testing multiple offers</p><p>Team also provides import and export feature that allow ops team to migrate rules from sandbox to production environment easily</p><h3>Audience Targeting</h3><p>Since rules/conditions for audience targeting are similar with qualification rules. The marketing team should be able to define a set of rules with any kind of data to select an appropriate customer segment for a campaign. Therefore, the same Rule Builder and Rule Engine are used for this purpose since we can leverage its powerful features with very small efforts</p><h3>Conclusion</h3><p>This design/architecture is not only able to serve a large number of users at peak time such as hot deal campaigns, but also able to operate by non technical users, so that engineering team can focus on developing features, while operation team has a powerful tool to offer the right things to right customers.</p><p>Thanks to support by ecosystem and domain driven design, we can solve complex business requirements with acceptable efforts and timeline. This is the 2nd version after engineering team spent one year for supporting daily operation since the 1st version didn’t provide tool for operation team</p><p>It is rare case that you need to build a promotion system like this, but some patterns can be helpful and hope this helps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce6170ee4a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a realtime approval workflow for online lending]]></title>
            <link>https://medium.com/@hungdv136/how-to-build-a-realtime-approval-workflow-for-online-lending-eae6c28e9496?source=rss-c23220505de6------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae6c28e9496</guid>
            <category><![CDATA[digital-lending-journey]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[temporal]]></category>
            <dc:creator><![CDATA[Hung Dinh]]></dc:creator>
            <pubDate>Fri, 19 May 2023 02:50:04 GMT</pubDate>
            <atom:updated>2023-05-19T02:50:04.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*OHwihyUzpho4oe9YybOy8A.png" /><figcaption>Image: quixy.com</figcaption></figure><h3>Introduction</h3><p>Credit cards and personal loans are getting popular nowadays, but underwriting process is still complex and time-consuming due to regulations and risks. Users need to provide a lot of documents such as labor contract, bank statement, household book, ID card, … and wait for a long time to get approval from bank. It significant impacts to user experience, limits customer base and sale volumes while increase the operation cost. Therefore, digital transformation is inevitable for lending. The biggest challenge with online lending is to prevent fraud effectively while can go mass to open market</p><p>First of all, we deep dive into some key non functional requirements for online lending workflow</p><p><strong>Support A/B testing</strong> with multiple flows, each flow can have a different banding styles, steps, business rules, … This is the most important feature, so that we can quickly optimize the journey and rules for each customer segment. Thus reduce drop off, increase the conversion rate and control risk effectively per channel. Furthermore, we can integrate with multiple lenders and partners with their own branding styles and risk appetite</p><p><strong>Flexibility</strong>: Integrate seamlessly with internal and external systems without impact to user experience regardless of its response time, uptime and throughput, … The lending decision rules require a wide range of input data from external vendors, those systems are slow and not stable. In addition, each lenders uses different dataset and rules.</p><p><strong>Scalability</strong>: Support realtime processing with high workload, low latency and high accuracy because each application might require to query dozen of data or a large amount of data, for example user images for realtime EKYC. Also it should be able to process a large number of events for realtime fraud prevention</p><p><strong>Traceability</strong>: Ability to quickly trace why a user is approved or rejected. This is not only required for analytic, but also required for customer support to quickly feedback for users</p><p><strong>Versioning</strong>: When a new workflow is approved and activated, existing users are still able to continue with the current workflows</p><p>Security: Rules should not be exposed to avoid fraudsters to know decision rules</p><h3>High Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*3pVGKs89uvEEIZm3m7Lm4Q.png" /><figcaption>High level design</figcaption></figure><p><strong>Web</strong>: This is a ReactJS application. It calls API to get the current state of an application by its id. Also, submit user’s provided data back to the backend via API. To support dynamic workflow, frontend should not handle any workflow logic. It always calls API to know which screen should be shown to user</p><p><strong>API</strong>: Expose API for frontend, return application state, persist data to database and produce event to brokers (Kafka). The decision output is not returned to frontend, instead API only return the next state (screen)</p><p><strong>Service Worker:</strong> Manage asynchronous tasks. To avoid blocking the user journey, service workers are responsible for listening to state changed events, matching with flow configurations to evaluate whether a data query job need to be triggered, for example CIC, score, … This is also to optimize cost of query data from external vendors such as CIC by not triggered if some conditions are not met. The collected data will be persisted to data store and also stream (CDC) to Kafka to notify the workflow. This design can also support any data pipeline to produce its processed data to workflow, for example: fraud prevention model</p><p><strong>Decision Workflow</strong>: Gathers queried data from service workers along with user’s provided data and other contextual data, feed to decision rules to evaluate application state which can be rejected, approved or a next state. Sometimes, if data is not ready and it is critical for final approval decision, the workflow needs to hold application by moving application to appraising state until that data is ready or reach max configured timeout. We should avoid blocking user journey if data is not ready at a middle step because it significantly increases drop off rate</p><p><strong>Decision Engine</strong>: Rules are defined by a policy language or DSL such as <a href="https://www.drools.org/">Drools</a>, <a href="https://github.com/hyperjumptech/grule-rule-engine">Grule</a>, <a href="https://github.com/Knetic/govaluate/blob/master/MANUAL.md">go-evaluate</a>, <a href="https://www.openpolicyagent.org/docs/latest/policy-language/">Rego</a>. Our first decision tree was built on top of go-evaluate, but due to the complexity (a few hundreds of rules), it is being migrated to <a href="https://www.openpolicyagent.org/docs/latest/policy-language/">Rego</a>for better documentation. The defined rules will be added to rule repository(database) and cached in-memory to support high traffic with low latency since it is critical for every step of every application (P99 &lt; 3ms)</p><p><strong>Configurations</strong>: Manage rules, flow definitions and data query configurations. These can be changed on demand by submitting new rules or adjust the existing one.</p><h3>Detail Design</h3><p>This section illustrates the detail design of service workers and workflow which are main components of system</p><p><strong>Service Workers</strong></p><p>There is a famous framework <a href="https://github.com/gocraft/work">go-craft</a> to handle background workers in Go. While its performance is good and easy to handle simple workflows, but it had some drawbacks:</p><ul><li>No built-in execution histories makes it is hard to trace once errors occur</li><li>Lacks of built-in support for monitor</li><li>It uses Redis to persist jobs, risky for long running tasks</li><li>It requires more efforts to handle workflow with multiple activities, not to mention a complex workflow</li></ul><p>Background workers can be handled with Kafka and <a href="https://temporal.io/">Temporal</a> as the following diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*toFD0mDk9BHvsgGngMhpIA.png" /><figcaption>Data query workflow</figcaption></figure><p>A consumer subscribes to a Kafka topic, checks whether configured rules are matched, then triggers an appropriate data processing activity based on configuration. The service configuration can be liked this</p><pre>{<br>  &quot;score&quot;: {<br>    &quot;enabled&quot;: true<br>    &quot;dispatch&quot;: [{<br>      &quot;event_type&quot;: &quot;state_changed&quot;<br>      &quot;event_name&quot;: &quot;ekyc_completed&quot;<br>      &quot;rule_name&quot;: &quot;trigger_query_score&quot;<br>    }]<br>  }<br>}</pre><p>In the above example, a worker subscribes to state changed event stream, it will trigger querying score if user completed verifying eKYC and rules are satisfied. The triggering rules can be defined as the following example. Rules are optional if not defined, then worker will trigger the job whenever the defined event occurred</p><pre>package rule<br><br>import future.keywords.if<br><br>default allow := false<br><br>allow if input.score.value &gt;= 350</pre><p>The output will be { “allow”: true } if score &gt;= 350. You can try with this <a href="https://play.openpolicyagent.org/p/grEsxEpi3b">playground</a>. This rule will be pushed to decision engine along with other fields such as: name=trigger_query_score, engine_type=rego</p><p>With this design, when a new data type is required, we only need to add code to integrate with new service, mostly using RestAPI. After that new data type is available for any flow through its configurations</p><h4><strong>Decision Workflow</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*qm9QHpiH-BEyA00vwcrA7A.png" /><figcaption>User journey and business workflow</figcaption></figure><p>The above diagram is an example of user journey and decision workflow. It consists a set of steps and rules to move between steps. When user starts the journey, engine selects an appropriate flow based on configured strategy (latest, weighted random or round-robin). Decision workflow gathers collected data by service workers in Redis/DB, then feed collected data to decision engine via gRPC/HTTP to get the next state and approval status (rejected/approved). If required data is not ready, workflow holds the process until data is ready or exceeded max waiting time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*q3jCjp8oPMiMK9E0pMJzYg.png" /><figcaption>Decision workflow components</figcaption></figure><p>The flow configuration can be as following example. You can view the output with this <a href="https://play.openpolicyagent.org/p/XIeC5LUHlf">playground</a>. The engine will traverse on output tree until node name matches with the current application step name, then get the next state. The input and output will be persisted to database for tracing later. If you look at the output, you can see that all condition variables are included in the output. It is easily to trace back later even application data changed after that</p><pre>package rule<br><br>import future.keywords.if<br><br># Variables<br>ui_version := &quot;v1.0.0&quot;<br>is_vip := input.preselection.type == &quot;vip&quot;<br><br># Flows<br>flows := [<br> {<br>  &quot;name&quot;: &quot;step_1&quot;,<br>  &quot;screen_name&quot;: &quot;screen_1&quot;,<br> },<br> {<br>  &quot;name&quot;: &quot;step_2&quot;,<br>  &quot;screen_name&quot;: &quot;screen_2&quot;,<br>  &quot;branches&quot;: [<br>   {<br>    &quot;name&quot;: &quot;vip&quot;,<br>                &quot;ui_version&quot;: &quot;v1.0.0-vip&quot;,<br>    &quot;matched&quot;: is_vip,<br>    &quot;flows&quot;: [<br>     {<br>      &quot;name&quot;: &quot;vip.screen_1&quot;,<br>      &quot;screen_name&quot;: &quot;vip_screen_1&quot;,<br>     },<br>     {<br>      &quot;name&quot;: &quot;vip.screen_1&quot;,<br>      &quot;screen_name&quot;: &quot;vip_screen_2&quot;,<br>     },<br>    ],<br>   },<br>   {<br>    &quot;name&quot;: &quot;normal&quot;,<br>    &quot;matched&quot;: is_vip == false,<br>    &quot;flows&quot;: [<br>     {<br>      &quot;name&quot;: &quot;normal.screen_1&quot;,<br>      &quot;screen_name&quot;: &quot;normal_screen_1&quot;,<br>     },<br>     {<br>      &quot;name&quot;: &quot;normal.screen_1&quot;,<br>      &quot;screen_name&quot;: &quot;normal_screen_2&quot;,<br>     },<br>    ],<br>   },<br>  ],<br> },<br> {<br>  &quot;name&quot;: &quot;completed&quot;,<br>  &quot;screen_name&quot;: &quot;completed&quot;,<br> },<br>]</pre><p>User Interface</p><p>I have described how to configure workflows and decision rules, we can enable a new workflow and its business rules by configurations, but how can end users interact with that workflow? I think that user interfaces should be developed by ReactJS to able to provide a best user experience as possible. There are some frameworks to provide user interface by configuration (no code), but using these framework has some drawbacks as the following</p><ul><li>Non-tech users are not able to configure since it still requires technical background and sometimes requires to customize. Thus, developers are fully responsible for configuration. If so, we should not limit them with the framework, it reduces their productivity significantly, developers should be able to choose what suitable with them (ReactJS)</li><li>There are limitations with that kind of framework, it is not easy or take times to implement complex screens.</li></ul><h3>Summary</h3><p>I have summarized high level design and concepts of building a dynamic realtime approval workflow. This design scales well because of the following reasons</p><ul><li>Asynchronous processing: Most of tasks are executed asynchronously with user journey. It significantly improves user experience, system can trigger data processing job as soon as possible. Failure tolerance is better, especially when system needs to communicate with few unstable systems</li><li>In-memory rules execution: Rules are executed by Go in memory, make it easy to scale</li><li>Flexibility: developers can choose suitable options, because rules and workflow are complex, it will significant impact to delivery speed if limit them with no-code solutions</li></ul><p>However, it still needs engineers to involve in every setup steps (rules, flows, user interface and automation tests</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae6c28e9496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking Outbound HTTP or gRPC Requests in Go]]></title>
            <link>https://medium.com/@hungdv136/mocking-outbound-http-grpc-requests-in-golang-f98407310958?source=rss-c23220505de6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f98407310958</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Hung Dinh]]></dc:creator>
            <pubDate>Tue, 16 May 2023 04:49:49 GMT</pubDate>
            <atom:updated>2023-05-18T10:41:27.494Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/zus-health/mocking-outbound-http-requests-in-go-youre-probably-doing-it-wrong-60373a38d2aa">This post</a> describes few approaches and frameworks for mocking outbound http requests in unit test for Go. In this story, I’m going to share another library named <a href="https://github.com/hungdv136/rio">Rio</a> that is being used internally for a long time ago, but it just has been published recently</p><h4>Unit test in Go</h4><p>Suppose that we want to test a simple function that calls an external API as the following example</p><pre>package example<br><br>import (<br> &quot;bytes&quot;<br> &quot;context&quot;<br> &quot;encoding/json&quot;<br> &quot;errors&quot;<br> &quot;net/http&quot;<br>)<br><br>func CallAPI(ctx context.Context, rootURL string, input map[string]interface{}) (map[string]interface{}, error) {<br> bodyBytes, err := json.Marshal(input)<br> if err != nil {<br>  return nil, err<br> }<br><br> req, err := http.NewRequestWithContext(ctx, http.MethodPost, rootURL+&quot;/animal&quot;, bytes.NewReader(bodyBytes))<br> if err != nil {<br>  return nil, err<br> }<br><br> req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> res, err := http.DefaultClient.Do(req)<br> if err != nil {<br>  return nil, err<br> }<br><br> if res.StatusCode != http.StatusOK {<br>  err := errors.New(&quot;not found&quot;)<br>  return nil, err<br> }<br><br> data := map[string]interface{}{}<br> decoder := json.NewDecoder(res.Body)<br> if err := decoder.Decode(&amp;data); err != nil {<br>  return nil, err<br> }<br><br> return data, nil<br>}</pre><p><a href="https://github.com/hungdv136/rio">Rio</a> offers a feature-rich and simple API to write concise test for our sample function. The source code for this example can be found <a href="https://github.com/hungdv136/rio_examples">here</a></p><pre>package example<br><br>import (<br> &quot;context&quot;<br> &quot;testing&quot;<br><br> &quot;github.com/google/uuid&quot;<br> &quot;github.com/hungdv136/rio&quot;<br> &quot;github.com/stretchr/testify/require&quot;<br>)<br><br>func TestCallAPI(t *testing.T) {<br> t.Parallel()<br><br> ctx := context.Background()<br> server := rio.NewLocalServerWithReporter(t)<br><br> animalName := uuid.NewString()<br> returnedBody := map[string]interface{}{&quot;id&quot;: uuid.NewString()}<br><br> require.NoError(t, rio.NewStub().<br>  // Verify method and path<br>  For(&quot;POST&quot;, rio.EndWith(&quot;/animal&quot;)).<br>  // Verify if the request body is composed correctly<br>  WithRequestBody(rio.BodyJSONPath(&quot;$.name&quot;, rio.EqualTo(animalName))).<br>  // Response with 200 and json<br>  WillReturn(rio.NewResponse().WithBody(rio.MustToJSON(returnedBody))).<br>  // Submit stub to mock server<br>  Send(ctx, server))<br><br> t.Run(&quot;success&quot;, func(t *testing.T) {<br>  t.Parallel()<br><br>  input := map[string]interface{}{&quot;name&quot;: animalName}<br>  resData, err := CallAPI(ctx, server.GetURL(ctx), input)<br>  require.NoError(t, err)<br>  require.Equal(t, returnedBody, resData)<br> })<br><br> t.Run(&quot;not_found&quot;, func(t *testing.T) {<br>  t.Parallel()<br><br>  // Request body does not match<br>  input := map[string]interface{}{&quot;name&quot;: uuid.NewString()}<br>  resData, err := CallAPI(ctx, server.GetURL(ctx), input)<br>  require.Error(t, err)<br>  require.Empty(t, resData)<br> })<br>}</pre><p>Rio verifies the method, path, body of the incoming request with predefined stub to assure that those are provided correctly, then returns appropriate response based on the matched stub. The returned value is explicitly asserted at the end of each test. This approach has some advantages</p><ul><li>The chaining and declarative style can help to write a concise and readable test</li><li>Everything is defined in the test, no global or external setup is easier to read and maintain test because we can see everything in one place</li><li>Test is isolated with other test cases, it can be run in parallel with other tests. It not only increases test speed, but also can freely change test logic without affecting to other test cases</li><li>No code pollution. There is no requirement for how to write function code (CallAPI), it can be wrote any convention/style, except that it must be able for caller to provide the base URL of the external system</li><li>Easily to test diverse scenarios like success and not found in the above example</li></ul><h4>How about integration tests</h4><p>If manual testers or automation test engineers want to test the above feature (suppose that it is exposed via Restful API), how can we mock the external outbound request? There are few mocking servers such as <a href="https://wiremock.org/">Wiremock</a>, C<a href="https://testinggospels.github.io/camouflage/">amouflage</a>, …</p><p>Rio also supports HTTP/gRPC mock servers, it has been used in our system for thousands of test cases since a few years ago because of the following reasons</p><ul><li>Support both gRPC and HTTP. Even I recommend that we should carefully consider to mock gRPC, but it is sometimes helpful to create boundary for a test case. The gRPC response can be defined in JSON format. Check <a href="https://github.com/hungdv136/rio/blob/main/README.md#mocking-grpc">this</a> to see how to mock gRPC server</li><li>Using a single mock library can help developers and testers share knowledge and stub definitions</li><li>Support Go, our developers are also responsible for writing integration tests. It is easier for them to write tests in Go</li><li>Support DSL in YAML/JSON format and also <a href="https://github.com/hungdv136/rio/blob/main/README.md#dynamic-response">dynamic response</a> for manual testers to setup mocks</li><li>Support rich features for complex scenarios since it is being used as a single mock library in our systems for a long time and is actively maintained by developers</li></ul><p>Check <a href="https://github.com/hungdv136/rio/blob/main/README.md">this link</a> to see how to use Rio for integration tests</p><h4>Final Thoughts</h4><p>I have introduced a new library for mocking http request in unit test and integration test in Go, so that you can help another choice depending on your situation. In my experience, you should choose the library/approach that can make your tests don’t depend on any global setup, assertions and matching rules should be explicitly defined within the tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f98407310958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An OOP Flux implementation in Swift]]></title>
            <link>https://medium.com/@hungdv136/an-object-oriented-programming-flux-implementation-in-swift-37dce512bda8?source=rss-c23220505de6------2</link>
            <guid isPermaLink="false">https://medium.com/p/37dce512bda8</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[flux]]></category>
            <dc:creator><![CDATA[Hung Dinh]]></dc:creator>
            <pubDate>Fri, 14 Jul 2017 16:16:42 GMT</pubDate>
            <atom:updated>2017-07-15T01:35:56.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, my name is Hung Dinh. I’m a senior iOS developer at <a href="https://www.hrcloud.com/">HRCloud Inc</a>. Today, I&#39;m going to talk about the problems we face when applying Flux Architecture to our products and how we customize Flux to <strong>fit</strong> this architecture with <strong>our projects </strong>(<em>you don&#39;t need to customize the original Flux if you are not having the same problems</em>).</p><p>This article assumes that you are already familiar with Flux but if not, here is a resource to get started:</p><p><a href="https://facebook.github.io/flux/docs/overview.html#content">Flux | Application Architecture for Building User Interfaces</a></p><p>One and a half year ago, I started studying Flux Architecture. After built few examples in Swift, I introduced my manager and coworkers to these examples along with Flux Architecture. Most of them were very interested in this new idea and we decided to apply this idea to our products on both iOS and Android platforms. However, there were a few questions that need us to clarify:</p><ol><li><strong>Can we release the stores if they are not being used anymore?</strong></li></ol><p>a. Problem</p><p>In Flux, the dispatcher is supposed to dispatch each action to all of the stores.</p><p>“<em>Each store registers itself and provides a callback. When an action creator provides the dispatcher with a new action, all stores in the application receive the action via the callbacks in the registry</em>” — <a href="https://facebook.github.io/flux/docs/in-depth-overview.html#a-single-dispatcher">Flux in depth overview</a></p><p>This means that all of them need to be keep alive along with the application, even they are not being used in any views. We should find out an approach to release unused stores to reduce memory usage.</p><p>b. Approach</p><p>After investigating, we all agreed that an action should do a single job (Single Responsibility) and it mostly affects to only one store. If other stores need to be updated when executing that action, another action should be dispatched inside that one. Finally, we decided that an action won&#39;t be dispatched to every stores any more. Instead, each action should be dispatched to a specific store so that other stores can be gone away if it is not being used in any views.</p><p><strong>2. Can we avoid violating Open Close Principle in SOLID?</strong></p><p>a. Problem</p><p>In the original Flux implementation, when we add a new action, we also have to add a new ‘case’ statement into ‘reduce’ function in the store. The same problem when removing an action. That makes OOP folks like me confused if we are violating the Open Close principle in SOLID or not.</p><p>Here is an <a href="https://github.com/facebook/flux/blob/master/examples/flux-todomvc/src/data/TodoDraftStore.js">example for Todo application</a> that Facebook provides in GitHub.</p><p>b. Approach</p><p>An action should know what side-effect should be executed and how to transform the state by itself. So we add a new base Action class</p><pre>public class Action {<br>    // This pure function describes how to transform the state<br>    func reduce(state: State, sideEffectResult: Result) -&gt; State? </pre><pre>    // This is for executing side-effects like requesting API, ...<br>    func execute(state: State) -&gt; Result</pre><pre>    // This is to identify what store this action belongs to<br>    var store: Store&lt;State&gt; { get }<br>}</pre><p>With this approach, we don&#39;t have to modify the stores, what we should do is to create a new action inheriting from the base action above, then override the functions and property above. In addition, we can easily writing unit-test for that standalone action without having to writing unit-test for any store.</p><p>2. <strong>Is there any flexible way to manage dependencies between actions.</strong></p><p>a. Problem</p><p>In the real world, we need to manage the dependencies between actions, but it seems that the <strong><em>waitFor</em></strong> method that original Flux implementation provides can not cover some cases that we face. Let me give you some examples:</p><ul><li><strong>Example #1</strong>: User pulls to refresh, PullToRefreshAction will be fired. While this action is executing, user pulls to refresh again. How we cancel one of them?</li><li><strong>Example #2: </strong>We have these two actions A1, A2, both of them request to API asynchronously. A2 have to wait for A1 requests to API completely in order to be executed. How we control this flow?</li></ul><p>b. Approach</p><ul><li><strong>Example #1: </strong>Define a Rule as below, then attach to the store.</li></ul><pre>UniqueRule(PullToRefreshAction.self, cancelBehavior: .first, condition: Your-Closure)</pre><p>‘condition’ is an optional closure parameter that allows us to have more control about when should cancel the action.</p><p>‘cancelBehavior: .first’ means that the first action will be canceled. Otherwise, the latest action will be ignored.</p><ul><li><strong>Example #2:</strong></li></ul><pre>SequenceRule(A1.self, A2.self, condition: your-closure)</pre><p>Or we can define new rules by inheriting protocol Rule.</p><pre>protocol Rule {<br>    func execute(a: ExecutingAction, actions: [ExecutingAction])<br>}</pre><p><strong>3. Can we execute actions in a background thread?</strong></p><p>a. Problem</p><p>Since we have actions executing in sequence that i have said in the above question. The Dispatcher will need more time to execute queued actions. That might causes the UI not responsive if we dispatch and execute actions in the UI thread like original Flux does.</p><p>b. Approach:</p><p>Our dispatcher will dispatch and execute actions in the background thread. After completed any action, state changes will be propagated to UI in the UI thread.</p><h3><strong>Example</strong></h3><p>To demonstrate how the customizations work, lets implement a simple demo application: <strong>CounterExample</strong></p><p>Firstly, create a new store named CounterStore</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44975bf61fc4e938e080c4fa34c7bbe1/href">https://medium.com/media/44975bf61fc4e938e080c4fa34c7bbe1/href</a></iframe><p>Secondly, add a new action named IncreaseAction</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08f1ecb09192eaf10bf5910b3e27e368/href">https://medium.com/media/08f1ecb09192eaf10bf5910b3e27e368/href</a></iframe><p>Finally, dispatch this action from ViewController</p><pre>IncreaseAction(additionValue: 1).dispatch()</pre><p><strong>That’s all for a simple counter application.</strong></p><p>In the next example, I’m going to introduce you how to do some side-effects like calling API, reading database or doing intensive calculation.</p><p>Create a new action ComplexAction, override ‘execute’ method and implement side-effects logic inside this method. In this example, we suppose that the ‘execute’ method returns an integer value after doing a long task that takes 5 seconds to complete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b343bd0ed01dbb73df1e199370f708b1/href">https://medium.com/media/b343bd0ed01dbb73df1e199370f708b1/href</a></iframe><p>Everything is ready. From the ViewController, dispatch the action:</p><pre>ComplexAction().dispatch()</pre><p>The source code for these example is available on GitHub at <a href="https://github.com/hungdv136/rx.flux-counter-example">https://github.com/hungdv136/rx.flux-counter-example</a></p><p>If you are interested in this approach, please visit <a href="https://github.com/hungdv136/rx.flux">https://github.com/hungdv136/rx.flux</a>.</p><p>If you have any concerns, please leave a comment.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37dce512bda8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>