Thursday, May 13, 2021

System design: CQRS pattern | MY 60 minutes study | CQRS documents by Greg Young

May 13, 2021

Introduction

It is the most challenge thing to learn by book reading. I like to use blogger to help me, track every minute and also highlight things new to me. 

CQRS document by Greg Young

Page 46/56

Event Storage as a Queue 

It has been previously discussed that the events coming out of a domain are also an [Integration Model]. Very often these events are not only saved but also published to queue where they are dispatched asynchronously to listeners either within the same system (the reporting model is a good example) or to other applications. An issue that exists with many systems publishing events is that they require a two phase commit between whatever storage they are using (Relational or otherwise) and the publishing of their events to the queue. 

The reason that the two-phase commit is needed is that a catastrophe could occur during the small period of time between when the write to the data storage commits and when the write to the queue commits. If a failure were to happen during this period the message would not be published on the queue (or if the other direction it may be published but the change may not be saved). If either case were to happen the listeners of the events would be out of sync with the producer.

The two-phase commit can be expensive but for low latency systems there is a larger problem when dealing with this situation. Generally the queue itself is persistent so the event becomes written on disk twice in the two-phase commit, once to the Event Storage and once to the persistent queue. Given for most systems having dual writes is not that important but if you have low latency requirements it can become quite an expensive operation as it will also force seeks on the disk. Figure 5 illustrates the two phase commit between data storage and a publishing queue. 

Some try to get around this problem by only writing to a queue then have something on the other side of the queue update the data storage with the changes represented by the events, this however has some issues. The largest issue is that not all of the events will be able to be written to the storage, eventual consistency has been introduced and it is possible that an optimistic concurrency problem will occur on the write of the events. Dealing with this problem in a production system is non-trivial. 

Many organizations do the opposite, use the event storage as a queue. Adding a sequence number to the Events table previously discussed allows the use the Event Storage as a queue. Figure 5 illustrates the change to the schema of the Events table. 

The database would insure that the values of sequence number would be unique and incrementing, this can be easily done using an auto-incrementing type. Because the values are unique and incrementing a secondary process can chase the Events table, publishing the events off to the queue. The chasing process would simply have to store the value of the sequence number of the last event it had processed, it could even update this value with a two-phase commit bringing the update and the publish to the queue into the same transaction. This process can be seen in Figure 7.

The work has been taken off of the initial processing in a known safe way. The publish can happen asynchronously to the actual write. This lowers the latency of completing the initial operation, it also will limit the number of disk writes in the processing of the initial request to one. This strategy can be extremely valuable when dealing with low latency requirements as it allows much of the work on the initial processing to be offloaded to another process asynchronously and in a safe way, there is little difference whether the publish happens as part of the initial processing or asynchronously as generally messages are published asynchronously anyways, using the Event Store as a queue just raises the time until the message is actually published slightly, this can be viewed as slightly raising the SLA.

CQRS and Event Sourcing

CQRS and Event Sourcing become most interesting when combined together. This chapter looks at the intersection of these two concepts within a system where Domain Driven Design has been applied.

CQRS and Event Sourcing have a symbiotic relationship. CQRS allows Event Sourcing to be used as the data storage mechanism for the domain. One of the largest issues when using Event Sourcing is that you cannot ask the system a query such as “Give me all users whose first names are ‘Greg’”. This is due to not having a representation of current state. With CQRS the only query that exists within the domain is GetById which is supported with Event Sourcing.

Event Sourcing is also very important when building out a non-trivial CQRS based system. The problem with integration between the two models is a large one. The maintaining of say relational models, one for read and the other for write, is quite costly. It becomes especially costly when you factor in that there is also an event model in order to synchronize the two. With Event Sourcing the event model is also the persistence model on the Write side. This drastically lowers costs of development as no conversion between the models is needed.

The original stereotypical architecture with using commands in Figure 1 can be compared to Figure 2 CQRS with Event Sourcing and found to be roughly equivalent amounts of work.

Cost Analysis

The client will be identical amounts of work between the two architectures. This is because the client operates in the exact same way. In both architectures the client receives DTOs and produces Commands that tell the Application Server to do something.

The queries between the two models will also be very similar in terms of cost. In the stereotypical architecture the queries are being built off of the domain model, in the CQRS based architecture they are being built by the Thin Read Layer projecting directly to DTOs. As was discussed in “Command and Query Responsibility Segregation” the Thin Read Layer should be equally or in some cases less expensive.

 The main differentiation between the two architectures when looking at cost is in the domain model and persistence. In the stereotypical architecture an ORM was doing most of the heavy lifting in order to persist the domain model within a Relational Database. This process introduces an Impedance Mismatch between the domain model and the storage mechanism, the Impedance Mismatch as discussed in “Events as a Storage Mechanism” can be highly costly both in productivity and the knowledge that developers need to have.

The CQRS and Event Sourcing based architecture does not have an Impedance Mismatch between the domain model and the storage mechanism on the Write side. The domain produces events, these same events are all that is stored. The usage of events is all that the domain model knows about. There is however an impedance mismatch in the read model. The Event Handlers must take events and update the read model to its concept of what the events mean. The Impedance Mismatch here is between the Events and the Relational Model.

The Impedance Mismatch between events and a Relational Model is much smaller than the mismatch between an Object Model and a Relational Model and is much easier to bridge in simple ways. The reason for this is that the Event Model does not have structure, it is representing actions that should be taken within the Relational Model.

Looked at from this perspective, the two architectures have roughly the same amount of work being done. Its not that its a lot more work or a lot less work; its just different work. The event based model may be slightly more costly due to the need of definition of events but this cost is relatively low and it also offers a smaller Impedance Mismatch to bridge which helps to make up for the cost. The event based model also offers all of the benefits discussed in “Events” that also help to reduce the overall initial cost of the creation of the events.

Integration

Everything up until this point has been comparing the systems in isolation. This rarely happens within an organization. More often than not organizations do only rely on systems but on systems of systems that are integrated in some way.

With the stereotypical architecture no integration has yet been supported, except of course perhaps integration through the database which is a well established anti-pattern for most systems. Integration is viewed as an afterthought.

The integration must be custom written. Many organizations choose to build services over the top of their model to allow for integration. Some of these services may be the same services that the clients use but more often than not there is additional work that must be done in order to support integration.

A larger problem exists when the product is being delivered to many customers. It is the teams responsibility to provide hooks for all of the customers and how they would like to integrate with thesystem. This often becomes a very large and unwieldy piece of code, especially on systems that are installed at hundreds or thousands of different clients all of which have different needs. The business model here tends to be to bill the client for each piece of custom integration, this can be quite profitable but it is a terrible model in terms of software. 

With the CQRS and Event Sourcing based model, integration has been thought of since the very first use case. The Read side needs to integrate and represent what is occurring on the Write Side, it is an integration point. The integration model is “production ready” all throughout the initial building of the system and it is being tested throughout by the integration with the Read Side.

The event based integration model is also known to be complete as all behaviors within the system have events. If the system is capable of doing something, it is by definition automatically integrated. In some circumstances it may be desirable to limit the publishing of events but it is a decision to limit what is published as opposed to needing to write code to publish something.

The event based model is also by nature a push model that contains many advantages over the pull model. If the stereotypical architecture desired a push based model then there would be large amounts of work added to track events and ensure that they were synchronized with what the system recorded in its own data model.

Differences in Work Habits

The two architectures also differ greatly in parallelization of work. In the stereotypical architecture work is generally done in vertical slices. There are four common methodologies used.

  • Data Centric: Start with database and working out. 
  • Client Centric: Start with client and work in. 
  • Façade/Contract First: Start with façade, then work back to data model then work finally implement client 
  • Domain Centric: Start with the domain model, work out to the client then implement data model 
These methodologies all have a commonality; they tend to work in vertical slices. The same developers will work on a feature through these steps. The same can be done with the CQRS and Event Sourcing based architecture but it does not need to be. Consider a very high level view of the systems as contained in Figure 3.

The architecture can be viewed as three distinct decoupled areas. The first is the client; it consumes DTOs and produces Commands. The second is the domain; it consumes commands and produces events. The third is the Read Model; it consumes events and produces DTOs. The decoupled nature of these three areas can be extremely valuable in terms of team characteristics.

Parallelization

It is relatively easy to have five to eight developers working on vertical slices at a given point without running into too many conflicts in what is being done. This is because for a small number of developers it is relatively easy to communicate what each developer is working on and to insure that there are few if any areas where developers overlap. This problem becomes much more difficult as you scale up the number of developers.

Instead of working in vertical slices the team can be working on three concurrent vertical slices, the client, the domain, and the read model. This allows for a much better scaling of the number of developers working on a project as since they are isolated from each other they cause less conflict when making changes. It would be reasonable to nearly triple a team size without introducing a larger amount of conflict due to not needing to introduce more communication for the developers. They still communicate in the same way but they communicate about smaller decoupled pieces. This can be
extremely beneficial when time to market is important as it can drastically lower the amount of calendar time to get a project done. 

All Developers are not Created Equally

There, it has been said. On a team there are many different types of developers, some attributes to consider in differences amongst developers include

  • Technical Proficiency 
  • Knowledge of the Business Domain 
  • Cost 
  • Soft Skills  
The points of decoupling are natural and support the specialization of teams in given areas. As an example in the domain, the best candidate is a person who is high in cost but also has a large amount of business knowledge, technical proficiency, and soft skills to talk with domain experts. When dealing with the read model and the generation of DTOs this is simply not the case, it is a relatively straight forward thing to do. The requirements are different which often leads to the next item.

Outsourcing

It is often not cost effective to keep low cost, medium skilled developers on a team. The overhead of keeping employees in terms of salary costs as well as compliance with various governmental regulations is often not worth the benefits of having the developers as employees. If a company is in a high cost locale, the company can certainly get cheaper developers offshore. Whether offshore or onshore the separation helps with successfully outsourcing part of a project.
 
Outsourced projects often fail because large amounts of communication are required between the outsourcers and the local team or domain experts. With these communications many problems can come up including time differences, cultural, and linguistic.

The Read Model as an example is an ideal area of the system to outsource. The contracts for the Read Model as well of specifications for how it work are quite concrete and easily described. Little business knowledge is needed and the technical proficiency requirements on most systems will be in the midrange.

The Domain Model on the other hand is something that will not work at all if outsourced. The developers of the Domain Model need to have large amounts of communications with the domain experts. The developers will also benefit greatly by having initial domain knowledge. These developers are best kept locally within the team and should be highly valued.

A company can save large amounts of capital by outsourcing this area of the system at a low risk, this capital can then be reinvested in other, more important areas of the system. The directed use of capital is very important in reaching a higher quality, lower cost system.

Specialization

A problem exists when working with vertical slices. The “best” developers, with best being defined as most valuable, work with the domain. When working with a vertical slice though anecdotal evidence suggests that they spend roughly 20-30% of their time in this endeavor. 

With the secondary architecture, the team of developers working with the domain spend 80+% of their time working with the domain and interacting with Domain Experts. The developers have no concern for how the data model is persisted, or what data needs to be displayed to users. The developers focus on the use cases of the system. They need only know Commands and Events. 

This specialization frees them to engage in the far more important activities of reaching a good model and a highly descriptive Ubiquitous Language with the Domain Experts. It also helps to optimize the time of the Domain Experts as opposed to having them sit idly while the “technical” aspects of vertical slices are being worked on. 

Only Sometimes 

There are many benefits offered through the separation but they do not need to be used. It is also quite common to have a normal sized team still work in vertical slices. There are benefits in terms of risk management amongst other things to having a small to medium sized team work in vertical slices of the whole system. 

The real benefit with the CQRS and Event Sourcing based architecture is that the option exists to bring it into three distinct vertical slices with each having its own attributes optimized as opposed to using a one size fits all mechanism.

 

 

 


 

Real estate investment: Abbotsford | 2015 - 2021 | Double the price | investment

2 33682 Marshall Road, Abbotsford, BC, V2S 1L1

Asking price: $360,000 dollars













A boutique strata of 12 units centrally located in a convenient neighbourhood. Easy access to HWY 1, Seven oaks Shopping Centre, local stores, U of FV, restaurants, hospital, sports, entertainment...Spacious 2 bed 2 bath corner unit featuring 8'11'' ceiling, many windows, a French-door style patio with lots of natural light and fresh air, gas fireplace, functional laundry room, and lots of storage in the kitchen and throughout the unit! Unique open courtyard concept with direct access to ground level patio, ideal for pet owners. No common hallways, your unit goes directly outside, feels like a townhouse! Includes 2 side-by-side parkings and 1 storage locker. Perfect opportunity for investors and first-time buyers! Don't miss out! Book private appointment now! (25674974)

Property Summary

Property Type
Single Family
Building Type
Apartment
Storeys
1
Title
Strata
Built in
1992
Annual Property Taxes
$1,493.94

Building

Bathrooms
Total
2
Interior Features
Appliances Included
Washer, Dryer, Refrigerator, Stove, Dishwasher
Fixtures Included
Drapes/Window coverings
Basement Type
None
Building Features
Style
Attached
Floor Space
1253 sqft
Building Amenities
Laundry - In Suite
Storage
Storage
Heating & Cooling
Fireplace
1

Real estate investment: Powell River | 2015 - 2021 | 100% return

May 13, 2021

Introduction

It is time for me to learn more about this island called Powell River. I wish that I can learn better how to invest on real estate. At that time, I was enjoying tennis, shopping road trips to USA, and so many other things. 

Powell River | 2015 - 2021 | 100% return

My ex-roommate purchased one bedroom condo near SFU campus, she could not afford the place so she rented it out to a SFU student asking $800 Canadian dollars. So she rented a small bedroom and became my roommate. 

She stayed in same house with me, and then she found a boy friend and got married, moved out. She sold the condo near SFU, made profit close to $100,000 dollars, and then she bought investment properties with her husband at Powell River. 

The house was close to $250,000 dollars with one acre in 2015, now the price doubles. 

Walk to home: 7 KM walk | Good neighborhood in Vancouver

May 12, 2021

Introduction

It is best time in the year to walk outside. I enjoy the weather and scenic view of city, and a small surprise called tree swing. I found a swing place on my route to home today. Good neighborhood. 

My pictures










I should pay attention to stock market. I should sell my 4500 shares of NOK stock at price of $5.10/ share, and then purchase back at $4.7/ share. The difference is over $1500 US dollars. 

DIY tree swing, here is the link. 

Wednesday, May 12, 2021

Leetcode discuss: 124. Binary Tree Maximum Path Sum

May 12, 2021

Here is the link. 

C# | Post order traversal | optimal time and space complexity | May 12, 2021

May 12, 2021
Introduction
The algorithm is to find maximum path sum in any given binary tree. The path can start from any node in the binary tree and end any node in the tree. So the brute force solution will be time complexity O(N^3), using O(N^2) to find all paths first, and then use O(N) time to calculate the sum for each path. The optimal solution can be found using post order traversal once with time complexity is O(N), whereas N is total number of nodes in the tree.

It is important to undersand the post order traversal and how the traversal can help to traverse each node once and get all calculations needed for the maximum path sum in the binary tree. The tip here is that there are four values to calculate for each node in the tree, which is listed in the following section. I came cross this tip when I reviewed my study notes back in 2015 through my coding blog, and I definitely was surprised to learn the summary is simple and straightforward.

Post order traversal | bottom up | hashmap or in-place | Four cases
The idea is to apply post order traversal, visit nodes in binary tree bottom up, and also using optimal time complexity O(N), space complexity O(1), visit each node once.

There are still multiple ways to approach the solution based on the analysis of recursive function to calculate the root to leaf node maximum path. One idea is to use memoization to save all node's maximum path to leaf node's sum in a hashmap, or work on a solution in place so that there is no need to use extra space. In place solution also can be interpreted in different ways for easy to understand.

One of ideas is to think about the following way:
For each node like following, there should be four ways existing for max path:
1. Node only
2. L-sub + Node
3. R-sub + Node
4. L-sub + Node + R-sub

Keep trace the four path and pick up the max one in the end.

Another idea is to think about the following way:
For each node, recursively calculate the maximum path sum from root node to leaf node. So there are three values and keep the maximum value.
1. Node only
2. L-sub + Node
3. R-sub + Node
Next it is to calculate the paths cross root node, and keep maximum path sum.

Courage to try optimal time complexity and in-place first
It is better to build habit to try optimal time complexity and in-place solution for this probem first, and then spend time on other solutions like extra space using hashmap, or time complexity with O(N^2) solution. Try all solutions in practice and compare the difference.

The following code passes online judge, the solution is optimal time complexity, O(N), N is total number of nodes in the tree, and also space complexity is O(1).

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public int MaxPathSum(TreeNode root) {
        if(root == null)
            return 0; 
        
        var maxCrossRoot = Int32.MinValue; 
        //Try to aim optimal time complexity O(N), bottom up, post order traversal, 
        // visit each node once, and then recursively build up the maximum path sum, cross root path's maximum value
        // Also, space complexity is O(1) besides using internal stack of recursive function
        applyPostOrderTraversal(root, ref maxCrossRoot);
        
        return maxCrossRoot; 
    }
    
    /// May 12, 2021 
    /// bottom up, visit every node once, keep time complexity O(N), N is total number of nodes in the tree
    /// Recursive function is designed to calculate the maximum value of the following three:
    /// 1. Root value
    /// 2. Root value + left subtree's value
    /// 3. Root value + right subtree's value
    /// The maximum path sum is called from root node to leaf node path maximum sum. 
    private int applyPostOrderTraversal(TreeNode root, ref int maxCrossRoot)
    {
        if(root == null)
            return 0; 
        
        var left = applyPostOrderTraversal(root.left, ref maxCrossRoot); 
        var right = applyPostOrderTraversal(root.right, ref maxCrossRoot); 
        
        var value = root.val;
        var current = value; 
        if(left > 0)
            current += left;
        if(right > 0)
            current += right; 
        
        maxCrossRoot = Math.Max(maxCrossRoot, current);
        
        var values = new int[]{value, value + left, value + right};
        
        return values.Max();        
    }
}

Azure architecture: In Chinese | Azure cloud architecture patterns | Sharding

 May 12, 2021

I like to spend time to read all the content in Chinese first, and then read English version to help me understand better. 

Here is the link. 


GTE stock | 100 days investment | $10,000 dollars | 10 lessons

May 12, 2021

Introduction

It takes time for me to learn how business works. I chose to invest on GTE.TO and GTE stock since it is a small capital, and also it is undervalued. I like to learn more about business, and also figure out ways to make profit. It is important for me to write down lessons I learn through those past 100 days. 

GTE stock | 100 days investment | $10,000 dollars | 10 lessons


  1. Understand myself as an investor better. 
  2. I think that it is better to invest $10,000 dollars and do not time the market. Stay in the market as a long term investor. 
  3. On earning day of first quarter, GTE.TO went up 20% and I should have sold all positions. In theory, it should be highest point in next three months. 
  4. I had chance to read more articles about GTE stock. 
  5. Understand debt issue of the company behind GTE stock. 
  6. The range of GTE stock price should be easy for me to trade and make some short term gains. 
  7. GTE stock should be under-valued. I think that staying long term as an investor. 
  8. Market up and down brings me opportunity to make profit. 
  9. I like to set up a good role model as an investor. I like to learn and share my investment through a wechat group. 
  10. Learn more about business, and learn how small business survives in pandemic. 

Tuesday, May 11, 2021

10 ideas to lose 20 lbs in 2021

 May 11, 2021

Introduction

I like to work on a short research to find 10 ideas to help me to go back to healthy weight as possible. Today I weigh 205 lb. I just started my fifth day to walk from office to home, and it took me less than two hours. I like to think about more ideas to help me lose 20 lbs in 2021. 

10 ideas

I do think that it is time for me to build a small community on wechat, and help me to work on ideas every day to stay fit. I also need to learn more about issues related to obesity weight. 

Here are 10 ideas to help me. 

  1. Spend at least two to three hours a week to study sports, focus on walking, running and tennis sports; 
  2. Talk to friends and get tips from them. At least two or three times a week; 
  3. Learn more ways to enjoy two hours walk after work around 6:00 PM; 
  4. Document each walk after work using different ideas. Be creative; 
  5. Stay safe and get more ideas how to wear face mask and enjoy walking; 
  6. Look for good protein while I try to put myself on diet; 
  7. Study more about safety on walking outdoor; 
  8. Spend less time on stock market, but work on long term goal, value investing; Control stress of investment, and focus on my fitness goal; 
  9. Play at least three hours tennis during weekend;
  10. Do more research on hay fever. Avoid taking anti-histamine more than two months a year. 



First vaccine: I got it on May 9, 2021, Moderna

May 11, 2021

I like to help to promote the knowledge to get vaccine to prevent Covid 19. It is important to take some risk to take vaccine instead of taking risk to get infected by Covid 19. 

I like to remind myself also to set high priority for my own safety and push myself to go back to my fitness training, walk to home every day from office, walk 7 KM and share my learning how to stay fit, and make my own personal health as highest priority as well. 



System design: CQRS pattern | My 60 minutes paper reading | CQRS documents by Greg Young

May 11, 2021

Here is the article. 

Page  23/ 56

By applying CQRS the concepts of Reads and Writes have been separated. It really begs the question of whether the two should exist reading the same data model or perhaps they can be treated as if they were two integrated systems, Figure 5 illustrates this concept. There are many well known integration patterns between multiple data sources in order to maintain synchronisity either in a consistent or eventually consistent fashion. The two distinct data sources allow the data models to be optimized to the task at hand. As an example the Read side can be modeled in 1NF and the transactional model could be modeled in 3nf. The choice of integration model though is very important as translation and synchronization between models can be become a very expensive undertaking. The model that is best suited is the introduction of events, events are a well known integration pattern and offer the best mechanism for model synchronization.

Events as a Storage Mechanism 

Most systems in production today rely on the storing of current state in order to process transactions. In fact it is rare to meet a developer who has worked on a system that maintains current state in any other way. It has not always been like this. Before the general acceptance of the RDBMS as the center of the architecture many systems did not store current state. This was especially true in high performance, mission critical, and/or highly secure systems. In fact if we look at the inner workings of a RDBMS we will find that most RDBMSs themselves not actually work by managing current state! The goal of this section is to introduce the concept of event sourcing, to show the benefits, to show how a simple event storage system can be created utilizing a Relational Database for underlying data management.

Page 37/ 56

Case study: Purchase items previously in shopping cart 

There are however other types of queries that are becoming more and more popular in business, they focus on the how. Examples can commonly be seen in the buzzword “Business Intelligence”. Perhaps there is a correlation between people having done an action and their likelyhood of purchasing some product? These types of questions generally focus on how something came into being as opposed to what it came out to be. 

It is best to go through an example. There is a development team at a large online retailer. In an iteration planning meeting a domain expert comes up with an idea. He believes that there is a correlation between people having added then removed an item from their cart and their likelihood of responding to suggestions of that product by purchasing it at a later point. The feature is added to the following iteration. 

The first hypothetical team is utilizing a stereotypical current state based mechanism for storing state. They plan that in this iteration they will add tracking of items via a fact table that are removed from carts. They plan for the next iteration that they will then build a report. The business will receive after the second iteration a report that can show them information back to the previous iteration when the team released the functionality that began tracking items being removed from carts.  

This is a very stereotypical process, at some organizations the report and the tracking may be released simultaneously but this is a relatively small detail in the handling. From a business perspective the domain experts are happy, they made a request of the team and the team was able to quickly fulfill the request, new functionality has been added in a quick and relatively painless way. 

The second team will however have quite a different result. The second team has been storing events; they represent their current state by building up off of a series of events. They just like the first team go through and add tracking of items removed from carts via a fact table but they also run this handler from the beginning of the event log to back populate all of the data from the time that the business started. They release the report in the same iteration and the report has data that dates back for years. 

The second team can do this because they have managed to store what the system actually did as opposed to what the current state of data is. It is possible to go back and look and interpret the old data in new and interesting ways. It was never considered to track what items were removed from carts or perhaps the number of times a user removes and items from their cart was considered important. These are both examples of new and interesting ways of looking at data.

Argument or statement? It is true to learn the following claim. 

As the events represent every action the system has undertaken any possible model describing the system can be built from the events. 

Page 41 - 58

Building an Event Storage 

In “Events as a Storage Mechanism” the concept of rebuilding state from a series of events was looked at from a conceptual viewpoint. This chapter will focus on the implementation of an actual Event Storage and some of the issues that come up in producing an implementation. 

The implementation discussed in this chapter is not intended to be a production quality Event Storage, more so it is provided as a discussion point around how to build an Event Storage. The implementation here although not highly performant could meet the needs of a large percentage of applications that are built today. 

For the explanatory implementation it is easiest to build the Event Storage in an existing technology such as a RDBMS. This will alleviate many of the technical issues that can arise that are out of the scope of a basic discussion on how to build an event storage such as transaction commit models or data locality for read performance. 

Structure 

A basic Event Storage can be represented in a Relational Database utilizing only two tables. 

  • Column Name  Column Type 
  • AggregateId      Guid 
  • Data                   Blob 
  • Version              Int 

Figure 19 Table Layout for Events Table 

This table represents the actual Event Log. There will be one entry per event in this table. The event itself is stored in the [Data] column. The event is stored using some form of serialization, for the rest of this discussion the mechanism will assumed to be built in serialization although the use of the memento pattern can be highly advantageous. 

The table is shown with the minimum amount of information possible, most organizations would want to add a few columns such as the time that the change was made or context information associated with the change. Examples of context information might include the user that initiated the change, the ip address they sourced the change from, or their level of permission when they sourced the change. 

A version number is also stored with each event in the Events Table. This can generally be thought of as an increasing integer for most cases. Each event that is saved has an incremented version number. The version number is unique and sequential only within the context of a given aggregate. This is because Aggregate Root boundaries are consistency boundaries. 

The [AggregateId] column is a foreign key that should be indexed; it points to the next table which is the Aggregates table.


 

 

Weight control: How to Lose Weight by Walking 2 Hours | My 20 minutes study

May 11, 2021 

Here is the article. 

1. Walk Every Other Day

Walk every other day for two hours at a moderate pace. If you are new to walking, aim to maintain a speed of 3.5 mph for the duration of the walk. According to Harvard Health Publishing, you'll burn 596 calories in two hours of walking if you weigh 155 pounds.

Consider this your training period. All athletes, and even weekend warriors who walk/run a 5K, abide by a training schedule in order to acclimatize themselves to their chosen activity and to workout safely.

2. Walk for Shorter Times

Break down your walk into shorter intervals. If you find it difficult to walk continuously for two hours, break the walk down into two 60 minute walks or three 40-minute walks. The Physical Activity Guidelines for Americans recommends at least 150 to 300 minutes of moderately intense cardio — which includes walking — a week to maintain or lose weight.

Considering that you hope to do 840 minutes a week, weight loss is almost guaranteed, depending on the speed of your walk.

Read more: How Much Do You Have to Walk to Lose Weight?

3. Increase Speed Gradually

Increase your speed at a gradual rate until you reach a brisk pace of 4 mph. Someone who weighs 185 pounds will burn a total of 800 calories in two hours. Whether you can keep up this level of speed every day for two hours depends on your ultimate goal. To lose weight, yes, but to become strong and fit, consider adding strength-training workouts at least twice a week.

4. Eat for Walking

Plan your meals around your walking routine. Ward off hunger and keep your energy up for the two hours you are walking by eating a snack made up of a lean protein and complex carbohydrates. An example would be low-fat fruit yogurt, a whole grain bagel and peanut butter or a turkey sandwich.


Consume a high protein snack within 30 minutes of the end of your workout. Examples include a protein bar, protein shake, chocolate milk, a serving of almonds or a low-fat cheese stick.

Read more: One Easy Exercise With 31 Proven Health and Fitness Benefits

5. Add Some Challenge

Make your walks more challenging. To lose even more weight, use a treadmill to increase the incline of your walk. Begin at 1 percent and increase the incline until you reach 7 percent. Or if you crave being out in nature, find some hilly terrain and start climbing.

ACE Fitness, a long-time proponent of HIIT or high-intensity interval-training workouts, suggests adding intervals to your treadmill workout. It's doubtful you could keep up the intensity for two hours, but you can lose weight by committing to a HIIT workout on the treadmill in less time.


References


Walking: My 20 minute study | I Get Tired Quickly When Walking

I Get Tired Quickly When Walking

The Centers for Disease Control and Prevention recommend that healthy adults get at least 30 minutes of physical activity on a daily basis. Unfortunately, when you have trouble getting those 30 minutes every day, the recommendation often feels more like an insurmountable task. The CDC recommends walking as an excellent form of exercise, but if you tire quickly when just walking, it's time to explore some of the reasons why your body is fatiguing so soon and how to increase your aerobic endurance for daily fitness.

Why You're Tired

A variety of causes can contribute to your lack of aerobic endurance and all stem from the condition and efficiency of your heart. Being overweight places strain on the heart as it labors to pump blood through your body, reducing your endurance. Smokers usually have reduced endurance because they have reduced lung capacity and replace the oxygen in their blood with carbon monoxide, which is then pumped through the body. Even people who look physically fit can have low endurance if they don't exercise regularly, because their hearts aren't strengthened through workout and must labor to pump blood during the occasional aerobic workout, such as a brisk, long walk.

Aerobic Activity

Walking is one of the best, least injury-prone moves you can make toward better health. Your daily stroll is an effective aerobic activity because it raises your heart rate while having a low impact on your bones and joints. Regular aerobic exercise lowers your risks for cardiovascular disease, type 2 diabetes, obesity, balance problems and a host of other chronic conditions that diminish quality of life and can even affect your longevity. When you walk, you work the large muscle groups of the legs and feet -- you develop healthier, stronger quads, hamstrings, glutes, calves, feet and ankles, improve flexibility and boost circulation. A consistently sedentary lifestyle could leave you tired and fatigued after only a few minutes of walking.

Hydration and Daily Walks

If you feel tired after only a few minutes of walking, consider your lifestyle and how if affects your overall endurance. It helps to take a short break and rehydrate your body when you feel fatigued, since both dehydration and fatigue make it difficult to exercise. In the future, structure your walking so you're able to build up to longer distances by walking short distances on a daily basis, slowly increasing the amount of time you walk as your heart strengthens and your cardiovascular endurance improves. Start with several short walks each day to reach your 30 minutes, even if you can't manage it all at once.

Choose Endurance

That fatigued feeling you experience while walking is preventable by making the proper choices. If you're a smoker, stop. Smoking reduces the amount of oxygen in your blood and even reduces the effect exercise has on your body. If you're overweight, schedule an appointment and talk to your doctor about beginning a weight-loss regimen, complete with daily exercise and a healthy diet. As you rectify your poor lifestyle choices, your heart will thank you with increased endurance so you're able to walk daily and fulfill your physical fitness requirements. And check in with your physician, if you experience severe exhaustion while walking, to eliminate any medical conditions that could be draining your energy.

References