<?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 Yang(Bruce) Li on Medium]]></title>
        <description><![CDATA[Stories by Yang(Bruce) Li on Medium]]></description>
        <link>https://medium.com/@yangli907?source=rss-7677e5c0e78b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KVFKTrT_k2Hh_MtU.jpg</url>
            <title>Stories by Yang(Bruce) Li on Medium</title>
            <link>https://medium.com/@yangli907?source=rss-7677e5c0e78b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 06:25:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yangli907/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[Blog Digest — How Netflix Works (Part 2)]]></title>
            <link>https://medium.com/@yangli907/blog-digest-how-netflix-works-part-2-42be978feb66?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/42be978feb66</guid>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 17:01:01 GMT</pubDate>
            <atom:updated>2024-01-08T17:01:01.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>Blog Digest — How Netflix Works (Part 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*iH8JNosfjNcEiEeQ.png" /></figure><blockquote>This artical is a digest version of <a href="https://netflixtechblog.com/full-cycle-developers-at-netflix-a08c31f83249">this Netflix Engineering Blog Post</a></blockquote><h3>Full Cycle Developers at Netflix — Operate What You Build</h3><p>The journey of Netflix’s technical evolution from 2012 to 2018 reflects a paradigm shift in managing critical services. Initially, their operational challenges, such as cumbersome deployments, ineffective canarying, and difficulty resolving issues, were symptomatic of segmented responsibilities and communication gaps between ops-focused teams and developers. Faced with these obstacles, Netflix sought a transformative solution, leading them to experiment with various models, eventually culminating in the adoption of the “full cycle developer model.”</p><p>At the outset, Edge Engineering at Netflix, responsible for AWS services crucial to streaming, operated with separate ops-focused teams and SRE specialists. However, this arrangement created dependencies and communication challenges between developers and ops teams. Releasing new features involved coordination between devs and ops for metrics, alerts, and capacity considerations, followed by the handover of code for deployment and operation. While this reduced developer interruptions during smooth operations, it incurred significant costs when issues arose. Communication gaps and knowledge transfers between these distinct functional areas were inefficient, leading to longer time-to-detect and resolve deployment problems. This resulted in a widening gap between code completion and deployment, slowing down releases to a span of weeks instead of days. Consequently, feedback about operational issues trickled back to developers indirectly, hindering effective problem-solving.</p><p>Seeking to enhance this fragmented model, Edge Engineering experimented with a hybrid approach. Developers gained the capability to push code and were accountable for off-hours production issues and support requests. While this improved feedback loops for developers, the model was incomplete, leaving gaps in responsibility. Developers often deferred to ops specialists for deployments and pipeline debugging. Meanwhile, ops-focused individuals struggled to prioritize automation, perpetuating dependency on them.</p><p>In a pivotal move, Netflix’s Edge Engineering embraced a fundamental re-evaluation of their approach based on the core principles of the software life cycle. They recognized the need to optimize “time to value,” prompting a radical shift in their strategy.</p><p>The “full cycle developer model” emerged as a response. This transformative approach advocates for developers owning the entire software life cycle, encompassing design, development, testing, deployment, operations, and support. This holistic approach sought to address the shortcomings of siloed responsibilities by promoting shared ownership, breaking down barriers between teams, and leveraging tools and automation.</p><p>This transition empowered development teams to handle the entire life cycle, resulting in quicker issue resolution, reduced time-to-detect problems, and faster canarying. Centralized teams, like Cloud Platform, Performance &amp; Reliability Engineering, and Engineering Tools, were established at Netflix to develop common tools and infrastructure. These teams acted as force multipliers, providing reusable solutions and collaborating with development teams when common needs arose.</p><p>However, the full cycle developer model isn’t without trade-offs. It requires developers to balance breadth of responsibilities with deep expertise. While the approach favors broad knowledge across the life cycle, it escalates the cognitive load on developers. Additionally, while tooling and automation are crucial for scaling expertise, they cannot singularly address every challenge. There are inherent difficulties in driving adoption of centralized teams’ solutions across the organization, and achieving universal adoption remains a challenge.</p><p>Netflix acknowledges that this model suits its context and scale but might need adaptations for implementation elsewhere. The company recognizes the significance of analyzing the potential value and associated costs before transitioning. They advise evaluating the necessity of introducing complexity and encourage a mindset shift to adopt a similar model successfully.</p><p>In conclusion, Netflix’s journey from fragmented operational models to the full cycle developer model has been marked by experimentation, learning, and adaptation. This evolution has resulted in routine deployments, quicker canaries, and more agile issue resolution. The company, however, remains cognizant of the need for continual evolution to meet future demands. They advocate for careful consideration, mindful adaptations, and alignment with organizational needs while embracing similar models outside their specific context.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42be978feb66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blog Digest — How Netflix Works(Part 1)]]></title>
            <link>https://medium.com/@yangli907/blog-digest-how-netflix-works-part-1-1152e46d97d3?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1152e46d97d3</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[digest]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 19:51:24 GMT</pubDate>
            <atom:updated>2024-01-05T19:51:24.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>Blog Digest — How Netflix Works(Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*cFQsfQsAzFcCZjwi.jpeg" /></figure><blockquote>It’s a digest version of <a href="https://blog.bytebytego.com/p/netflix-what-happens-when-you-press">this ByteByteGo post</a> from ChatGPT.</blockquote><p>Netflix’s seemingly straightforward user interface conceals a highly intricate and sophisticated infrastructure. At first glance, one might assume that Netflix, a video streaming platform, relies solely on AWS (Amazon Web Services) to deliver its content. However, the reality is far more complex and fascinating.</p><p>In 2022, Netflix boasted an impressive user base of over 221.64 million subscribers spread across more than 190 countries. With a quarterly revenue of nearly $7.87 billion, the platform has become a dominant force in global internet traffic. The scale of its operations necessitates impeccable reliability, especially since Netflix operates on a subscription-based model.</p><p>Netflix’s operations are divided into three fundamental components: the client (the user interface), the backend (which primarily runs on AWS), and the content delivery network (CDN), known as Open Connect. This vertical integration ensures Netflix has complete control over the entire viewing experience on a global scale.</p><p>Initially, Netflix operated its own data centers, but due to reliability issues, it gradually transitioned entirely to AWS over eight years. Operating across three AWS regions, each with multiple availability zones, Netflix has fine-tuned a global services model that allows seamless user experience even during regional failures.</p><p>Contrary to the assumption that utilizing AWS would inflate costs, Netflix found that the cloud’s elasticity actually made it a cost-effective solution. AWS handles various aspects of their operations, such as scalable computing, storage, databases (utilizing DynamoDB and Cassandra), big data analytics, recommendations, and transcoding.</p><p>Transcoding, a massive operation at Netflix, involves converting videos to suit a myriad of devices, creating thousands of files tailored to different device specifications, network speeds, languages, and user preferences. This personalized approach even extends to header images, ensuring a unique and appealing experience for each user.</p><p>The platform’s experimentation with different CDN strategies sheds light on its evolution. Initially, Netflix built a small in-house CDN. Subsequently, it shifted to using third-party CDNs (such as Akamai and Limelight). Finally, it developed Open Connect, its custom CDN. Open Connect’s advantages in terms of quality, scalability, and cost-efficiency were evident due to Netflix’s deep understanding of user preferences and content delivery requirements.</p><p>This intricate infrastructure underpins the seemingly simple “press play” experience that users worldwide enjoy. It underscores Netflix’s unwavering commitment to delivering a seamless, personalized, and top-tier viewing journey for its subscribers.</p><p>The process of transitioning to AWS was pivotal for Netflix. Initially established in 1998 as a DVD rental service through the US Postal Service, Netflix began envisioning the future in on-demand streaming video. By 2007, it introduced its streaming video-on-demand service, allowing subscribers to access television series and films through various platforms. However, making this transition wasn’t without its challenges.</p><p>In 2007, when Netflix’s streaming service began, AWS’s EC2 (Elastic Compute Cloud) was still in its nascent stages, making it impractical for Netflix to launch using this cloud service. Consequently, Netflix built its two data centers adjacent to each other. However, this approach encountered the classic problems of lead times for equipment, capacity issues, and difficulty in maintaining reliability during rapid growth.</p><p>Operating a data center involves extensive work, from equipment procurement and installation to scaling up to meet increasing demand. Netflix faced challenges in building a reliable monolithic system that could accommodate its rapid growth. A critical turning point arrived in August 2008 when Netflix experienced a service outage for three days due to database corruption. This event highlighted their inadequacies in managing data centers and their core competency in delivering video content.</p><p>The outage prompted a crucial realization within Netflix. While they excelled at delivering video content, their expertise didn’t lie in building and maintaining data centers. They recognized that their focus should be on enhancing their strengths rather than diverting resources to areas that weren’t their core competency. Consequently, in a bold move, Netflix decided to shift to AWS.</p><p>The decision to move to AWS was driven by several key factors. One primary motivation was the pursuit of a more reliable infrastructure. Netflix aimed to eliminate single points of failure from its system and sought the highly reliable databases, storage, and redundant data centers offered by AWS. Additionally, AWS provided cloud computing capabilities that allowed Netflix to scale globally without the need to build and maintain their own data centers in different regions.</p><p>AWS’s proposition aligned with Netflix’s vision, as they sought to create a global service without the burden of managing their own data centers. The concept of “undifferentiated heavy lifting” was critical in Netflix’s decision-making process. AWS’s ability to handle tasks that were essential but didn’t directly contribute to Netflix’s core business of delivering a quality video-watching experience, meant Netflix could focus on providing business value.</p><p>The migration process from Netflix’s data centers to AWS was not immediate but extended over eight years. During this period, Netflix’s streaming customer base grew exponentially. The platform currently operates on several hundred thousand EC2 instances within AWS, a testament to its scale and reliance on the cloud service provider.</p><p>Transitioning to AWS significantly improved Netflix’s service reliability. While occasional downtimes aren’t entirely eliminated, the platform’s service has become notably more reliable than it was before. Netflix has taken extensive measures to enhance the reliability of its service within AWS.</p><p>Operating out of three AWS regions — North Virginia, Portland, Oregon, and Dublin, Ireland — Netflix operates across multiple availability zones within each region. While many companies typically operate from a single region, Netflix’s presence in three regions minimizes the impact of regional failures. In the event of a region failure, Netflix follows an evacuation strategy, seamlessly redirecting users to other operational regions within minutes.</p><p>The monthly evacuation tests conducted by Netflix simulate region failures to ensure their system’s readiness to handle such events. This global services model enables any customer to be served from any region, ensuring uninterrupted service even during regional outages.</p><p>Beyond improved reliability, migrating to AWS also yielded cost benefits for Netflix. Contrary to common assumptions, the cloud proved to be cost-effective for the platform. The cloud’s elasticity allowed Netflix to add or remove servers based on demand, optimizing costs by paying only for the resources they utilized.</p><p>Before pressing play on Netflix, numerous operations occur within AWS. The platform utilizes various AWS services for different functions, including scalable computing (EC2), scalable storage (S3), distributed databases (DynamoDB and Cassandra), big data processing, analytics, recommendations, and more.</p><p>Scalable computing (EC2) and storage (S3) are fundamental AWS services utilized by Netflix. The client devices, whether an iPhone, TV, Xbox, or Android phone, communicate with Netflix services running on EC2. Every action on the Netflix app, from browsing potential videos to seeking details about a specific video, involves interaction with an EC2-based system.</p><p>The platform leverages distributed databases like DynamoDB and Cassandra, which offer high-quality database solutions. These databases store a myriad of data, including user profiles, billing information, viewing history, and other crucial information across multiple servers to ensure data safety.</p><p>Netflix’s extensive collection of user data undergoes big data processing and analytics. The platform collects vast amounts of data regarding user viewing habits, preferences, and behaviors. Processing this data involves standardizing it into a uniform format, while analytics involves analyzing this data to derive insights and make informed decisions.</p><p>One remarkable instance of utilizing data analytics is in Netflix’s selection of header images. These header images, displayed for each video, aim to entice users to select a video. Netflix employs a data-driven approach, tailoring these images based on users’ preferences and viewing habits. These subtle customizations contribute to enhancing the user experience and engagement.</p><p>Transcoding is a massive operation at Netflix, crucial for delivering videos across various devices and network speeds. It involves converting videos into different formats and bitrates to accommodate various devices and internet connection speeds. For instance, a video might be transcoded into lower resolutions or bitrates for users with slower internet connections.</p><p>The complexity of transcoding is further amplified by the diversity of devices and platforms used by Netflix subscribers. Different devices and apps require videos in different formats and resolutions. Netflix uses its proprietary transcoding system to process and create multiple renditions of a video file to match various device specifications.</p><p>Moreover, transcoding extends beyond just adapting videos to different resolutions or bitrates. It includes multiple audio tracks and subtitles in various languages. This ensures that users across different regions and language preferences have a seamless viewing experience.</p><p>Netflix’s recommendation system is a core feature that significantly contributes to user engagement and satisfaction. AWS plays a pivotal role in this aspect by powering the algorithms that suggest personalized content to users. Netflix’s recommendation engine is known for its accuracy in predicting users’ preferences based on their viewing history, ratings, and interactions with the platform.</p><p>Netflix’s experimentation with different CDN strategies offers insights into its evolutionary journey. Initially, the platform developed a small in-house CDN to deliver its content. However, as the user base expanded, they faced challenges in maintaining the quality of service.</p><p>Subsequently, Netflix shifted to utilizing third-party CDNs, including Akamai and Limelight. While these third-party CDNs offered global coverage, they didn’t fully align with Netflix’s objectives. Netflix sought to provide a consistently high-quality streaming experience across the globe, necessitating a custom CDN solution.</p><p>The introduction of Open Connect, Netflix’s custom CDN, marked a significant shift. This CDN was designed to meet Netflix’s specific requirements, providing better control over content delivery, scalability, and cost efficiency. Open Connect strategically places caching servers within internet service provider networks, allowing for faster content delivery directly to users.</p><p>The custom CDN not only improved the quality of streaming but also reduced Netflix’s reliance on third-party providers, leading to cost savings. By utilizing Open Connect, Netflix could better manage its massive volume of traffic, resulting in enhanced streaming quality for its subscribers.</p><p>In essence, Netflix’s transition to AWS and its evolution in CDN strategies highlight its relentless pursuit of innovation, reliability, and user-centric services. The platform’s intricate infrastructure, spanning AWS services and its proprietary CDN, underscores its commitment to delivering a seamless, personalized, and top-tier viewing experience to its global subscriber base.</p><p>This continuous innovation and dedication to improving the streaming experience have solidified Netflix’s position as a leader in the entertainment industry. The platform’s ability to leverage technology, data analytics, and a deep understanding of user behavior has set new benchmarks for delivering high-quality streaming content worldwide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1152e46d97d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<Spring Microservices in Action> Reading Notes — Part 5]]></title>
            <link>https://medium.com/@yangli907/spring-microservices-in-action-reading-notes-part-5-91efeb41864?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/91efeb41864</guid>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Sun, 01 Mar 2020 06:10:52 GMT</pubDate>
            <atom:updated>2020-03-01T06:10:52.304Z</atom:updated>
            <content:encoded><![CDATA[<h4>Distributed Tracing and Event Processing</h4><h4>Distributed Tracing</h4><h4>What is Distributed Tracing?</h4><p>Unlike monolithic service, in microservice world, one client request usually is fulfilled by multiple underlying microservices, thus the distributed nature of such service structure demands a different way for troubleshooting.</p><p>The core procedure of distributed tracing consists of the following:</p><ol><li>Use a correlation id(request_id) as a linkage for transaction across services; (<em>Spring Cloud Sleuth</em>)</li><li>Log aggregation from multiple services; (<em>Papertrail</em>)</li><li>Data visualization, such as the calling sequence, duration of service call, etc. (<em>Zipkin</em>)</li></ol><h4>Trace ID and Span ID</h4><p>Instead of using previously mentioned request interceptor, filter and user context holder to create and pass correlation id, we can leverage Spring Cloud Sleuth to achieve the same purpose. Sleuth does the following:</p><ol><li>Create and inject correlation id to the service call;</li><li>Propagate the id to outbound service calls;</li><li>Surface the correlation id to logger such as slf4j.</li></ol><p>With the Sleuth dependency is configured in build script, the log statement will include the following additional trace information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*0gF_1NlUOaEvVod_" /></figure><p>note the difference between span id and trace id, the former is for each service call, whereas the latter is carried across all service calls within one request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*BjM5k8amKE5HLHpo" /></figure><h4>Log Aggregation</h4><p>Many log aggregation solutions can achieve the use case of consolidating logs from multiple servers in a centralized, queryable way. Such solutions including ELK, Splunk, Graylog, Sumo Logic and Papertrail. The overall architecture looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*tey1TcepLXwcDAtF" /></figure><p>The sample implementation using Papertrail is omitted in this post, the high level idea is to configure logger on all microservice hosts to write into Papertrail remote port, which will index and make the centralized logs queryable.</p><h4>Surfacing Trace(Correlation) ID in HTTP response</h4><p>By default, the added trace id is only available in log but never surfaced in HTTP response. In order to surface this info, we need to config Zuul service gateway to integrate the ResponseFilter with Sleuth and inject such correlation id. The code snippet is as below:</p><pre>package com.thoughtmechanix.zuulsvr.filters;<br>//Rest of annotations removed for conciseness<br>import org.springframework.cloud.sleuth.Tracer;<br>@Component<br>public class ResponseFilter extends ZuulFilter{<br>private static final int FILTER_ORDER=1;<br>private static final boolean SHOULD_FILTER=true;<br>private static final Logger logger = LoggerFactory.getLogger(ResponseFilter.class);<br>@Autowired<br>Tracer tracer;  // inject the tracer <br>@Override<br>public String filterType() {return &quot;post&quot;;}<br>@Override<br>public int filterOrder() {return FILTER_ORDER;}<br>@Override<br>public boolean shouldFilter() {return SHOULD_FILTER;}<br>@Override<br>public Object run() {<br>RequestContext ctx = RequestContext.getCurrentContext();<br>// add the trace id to response header. <br>ctx.getResponse()<br>➥ .addHeader(&quot;tmx-correlation-id&quot;, tracer.getCurrentSpan().traceIdString());<br>return null;<br>}}</pre><h4>Distributed Tracing using Zipkin</h4><p>To enable Zipkin Distributed Tracing visualization, we need to ensure</p><ol><li>Sleuth is configured to inject correlation id in the request,</li><li>Zipkin jar is installed with settings to capture trace data into the target Zipkin server (via spring.zipkin.baseUrl param in application yaml file)</li><li>Zipkin server is up and running. (by creating a Spring application with @EnableZipkinServer annotation, or use @EnableZipkinStream if the upstream data source is event stream such as <strong>RabbitMQ</strong> or <strong>Kafka</strong>)</li><li>Sampling strategy is defined to specify the trace data collecting policy. (via spring.sleuth.sampler .percentage application param, 0.5 means sending 50% of transactions info to Zipkin dash)</li></ol><p>Once the Zipkin pipeline is configured, you can use the Zipkin dashboard to query the service call lifespan, and discover more details of service call breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*DBLuvmiFmwezoSu3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*VUnyN9yUJeGz5QUj" /></figure><h4>Custom Span for fine-grained tracing</h4><p>It’s possible that we need to investigate the latency for a special service call, in this case the custom span allows us to add logging event before and after the call, then have Zipkin to surface this info in visualization. The code snippet is as below:</p><pre>package com.thoughtmechanix.organization.services;<br><br><br>@Service<br>public class OrganizationService {<br><br>@Autowired<br>private OrganizationRepository orgRepository;<br><br>@Autowired<br>private Tracer tracer;<br><br>@Autowired<br>SimpleSourceBean simpleSourceBean;<br><br>private static final Logger logger = LoggerFactory.getLogger(OrganizationService.class);<br><br>public Organization getOrg (String organizationId) {<br>    Span newSpan = tracer.createSpan(&quot;getOrgDBCall&quot;);<br>    logger.debug(&quot;In the organizationService.getOrg() call&quot;);<br>    try {<br>        return orgRepository.findById(organizationId);<br>    }finally{<br>        newSpan.tag(&quot;peer.service&quot;, &quot;postgres&quot;);<br>        newSpan.logEvent(org.springframework.cloud.sleuth.Span.CLIENT_RECV);<br>        tracer.close(newSpan);<br>    }<br>}</pre><p>Afterwards, the Zipkin shows the custom span info as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*SZFpMivoPjwWRthC" /></figure><h4>Event Driven Architecture in Spring Cloud</h4><h4>Why Event Driven?</h4><ol><li>Loosely couple No more direct service call to communicate state change from certain party. In synchronous design, if one side of the service is down, there will be either lost update or stale state, resulted in undesired service behavior. With messaging structure, two parties are completely decoupled, the state change is in the queue, and message consumer has no information on who publishes the message.</li><li>Durability With messaging queue, we can guarantee the message is eventually consumed by target service(s). We can use a watermark variable to store the last read message, to ensure latest batch of updates are fetched by the intended consumer(s).</li><li>Scalability When the messages in the queue are not consumed fast enough, we can spin up more consumers to process the data to accelerate. It greatly allows horizontal scaling of the service infrastructure.</li><li>Flexibility With messaging queue structure, we can easily add more consumers without impacting existing producer service and consumers.</li></ol><h4>Downside of Messaging Architecture</h4><ol><li>Messaging handling — if your use case requires strict message ordering, you’ll need to build the structure to handle it, which means each message cannot be essentially handled independently.</li><li>Message visibility and debuggability</li><li>Non-deterministic message ordering</li></ol><h4>Using Spring Cloud Stream</h4><p>Below is the high lever structure of Spring Cloud Stream:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*iXfI4iZhvJ_B0IdV" /></figure><p>The implementation details is omitted here on how to construct the message body, publish it to the source, then push it to a event bus channel.</p><h4>Use message to notify update, or send updated info?</h4><p>In general, we should not include full updated content itself in the message itself. Instead, we should just notify the updated ID and event type(such as “updated” or “removed”). This is to prevent the data staleness.</p><p>Imagine a message of “entity updated” is delayed, if we include the entity data itself, client will eventually get an outdated info inconsistent with data source. The ideal solution is to pass the entity id with type “updated”, so that consumer will fetch the latest entity info from data source based on the entity id.</p><h4>Producer Config</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*lEP8aFfPLQwGFP_Z" /></figure><h4>Consumer Config</h4><p>Below is the sample consumer side config for event listening and mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*fjgFu5AVK7ul7E71" /></figure><blockquote>The concept of a consumer group is this: You might have multiple services with each service having multiple instances listening to the same message queue. You want each unique service to process a copy of a message, but you only want one service instance within a group of service instances to consume and process a message</blockquote><h4>Distributed Caching</h4><p>In the messaging based workflow, whenever an update is received, service needs to lookup the resource id in the data source.</p><p>In order to reduce the load of data source, we can introduce the cache layer like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*qgDOTnbjAwnrC6Yq" /></figure><p>With this approach, the updates in the queue will trigger cache invalidation to update the cached content, so that Licensing service client above can query the latest data from the cache.</p><blockquote>You’ll have the licensing service always check a distributed Redis cache for the organization data associated with a particular license. If the organization data exists in the cache, you’ll return the data from the cache. If it doesn’t, you’ll call the organization service and cache the results of the call in a Redis hash. When data is updated in the organization service, the organization service will issue a message to Kafka. The licensing service will pick up the message and issue a delete against Redis to clear out the cache.</blockquote><p>Write Medium in Markdown? Try <a href="https://markdium.dev/">Markdium</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91efeb41864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<Spring Microservices in Action> Reading Notes — Part 4]]></title>
            <link>https://medium.com/@yangli907/spring-microservices-in-action-reading-notes-part-4-7ccbafd73532?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ccbafd73532</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[zuul]]></category>
            <category><![CDATA[gateway-service]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 07:22:24 GMT</pubDate>
            <atom:updated>2020-02-23T07:22:24.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>&lt;Spring Microservices in Action&gt; Reading Notes — Part 4</h3><h4>Client Resiliency and Service Routing</h4><h4>Client Side Resiliency</h4><h4>What can go wrong?</h4><p>In distributed microservice architecture, any subcomponent’s service degradation(such as slow response, or 5xx error) can have cascaded effort to its upstream services, which in turn propagates the issue across the system, and eventually take down entire application.</p><p>Furthermore, the consumer of certain service typically do not build handling for partial service degradation until the service is entirely whacked. For example, when the resource of a microservice(such as DB connection pool or threadpool) started to get saturated due to slow DB performance or network latency, its upstream consumer continue makes requests, until the downstream service can no longer handle any traffic.</p><h4>Client-side resiliency patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*i29Mwvr0hurRyCtF" /></figure><ol><li><strong>Client Load Balance (CLB)</strong>: discussed in previous post, we use Ribbon and Eureka to cache the service group info, and automatically mark / skip bad nodes, then round-robin to next available host and make another request. Since the service group info is cached locally, when service discovery host is temporarily not available, the service consumer can still rely on the cached info for host lookup operation.</li><li><strong>Circuit Breakers(CB)</strong>: Each outgoing remote call is monitored by CB, if the call is taking too long, the CB will kill the call based on timeout threshold, If enough calls failed in certain timeframe, CB will fail fast and prevent additional calls to this problematic service. Meanwhile, it’ll log and alert such service misbehavior to take further action, such as reboot or re-provision.</li><li><strong>Fallback Processing</strong>: Such mechanism allows defining a fallback method when the normal process failed. For example, if the SRP page failed to call ranking / recommendation service for front page listing, the fallback mechanism allows engineer to call another fallback method to return generic front page result. The fallback strategy works extremely well in situations where your microservice is retrieving data and the call fails</li><li><strong>Bulkheads</strong>: It’s to make sure each service has its own service specific remote resources(such as threadpool), so that when the calling volume to service A bursted, it won’t lead to service B’s threadpool saturation and potential rejection error. It allow allows scaling by service when different services have skewed volume distribution.</li></ol><h4>Circuit Breakers Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*YECx7mLW4sJOcGjb" /></figure><p>Above diagram shows how circuit breaker detects service degradation, and start fail fast or fallback routine when receiving further calls against the bad service.</p><p>Additionally, it will continuously “probe” the dysfunction service to check for recovery, and seamlessly restore the service communication when enough “probing” requests succeeded. Such auto detect and recovery saves effort from operation engineer to manually intervene, when issues can sometimes auto recover(such as temporary network outage, etc.)</p><p>In short, the CB allows 1) fail fast, 2) fail gracefully, and 3) recover seamlessly</p><p>Why fail fast? See below quotes from the book:</p><blockquote>First, if a remote resource is having performance problems, failing fast will prevent the calling application from having to wait for a call to time out. This significantly reduces the risk that the calling application or service will experience its own resource exhaustion problems and crashes.</blockquote><blockquote>Second, failing fast and preventing calls from service clients will help a struggling service keep up with its load and not crash completely under the load. Failing fast gives the system experiencing performance degradation time to recover.</blockquote><h4>Using Hystrix as circuit breaker</h4><p>We can enable Hystrix by simply annotate Spring Cloud application’s main class with @EnableCircuitBreaker, then annotate the service API method with @HystrixCommand. Afterwards, each call to the service method will be wrapped with Hystrix CB, then perform timeout and fallback mechanism accordingly, based on the annotation attributes.</p><p>When defining fallback method, the pass-in parameter must be the same as the original method, as all the params will be relayed to the fallback method.</p><p>Additionally, if we want to handle the Hystrix timeout exception, you can use try…catch to catch the HystrixRuntimeException at the point of target service method invocation.</p><p>Lastly, if your fallback method is to call another remote service, be sure to wrap the fallback method with @HystrixCommand.</p><h4>Using Hystrix for bulkhead pattern</h4><p>By default, all service calls use single shared threadpool for the Java container, if high load for a specific service happens, all services hosted in the JVM will eventually crash.</p><p>Hystrix supports segregated threadpools for individual service, so that each service can have threadpool with customized size, and the impact of threadpool saturation will not cascaded to other services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*FllJpU4nthC6N_3t" /></figure><p>Below formula is the recommended as the threadpool size:</p><pre>(requests per second at peak when the service is healthy <br>* 99th percentile latency in seconds) <br>+ <br>small amount of extra threads for overhead</pre><h4>Advanced Topics</h4><h4>ThreadLocal and Hystrix</h4><p>Details omitted for ThreadLocal, Hystrix concurrency strategy and isolation strategy(Thread vs. Semaphore) is described in Ch5.9. Details omitted now.</p><h4>Service Gateway and Zuul</h4><h4>Cross-cutting concerns and service gateway?</h4><p>When it comes to the use case of adding common behavior to all microservices in the application, such as logging, tracking and security, it’s usually not feasible to consistently implement and maintain such capabilities across all services due to several reasons:</p><ol><li><strong>Operational burden</strong> to maintain and update each involved microservice for the required common service capability. Every time when a change is introduced, we don’t need to change individual service and recompile/redeploy, which is a huge operational burden.</li><li><strong>Ensure cross-cutting behavior</strong>. By pull the common behavior for all services up at the gateway level, it mitigated the risk that certain service(s) may not have the needed behavior implemented.</li></ol><p>With service gateway, cross-cutting service concerns can be implemented in a single place without the individual development teams having to implement these concerns. The brief structure is like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*fu3aOdAY3YUvSwSC" /></figure><p>We can achieve the following use cases by using service gateway:</p><ol><li><strong>static routing</strong>: service consumer only needs to know service gateway VIP;</li><li><strong>dynamic routing</strong>: service gateway can inspect incoming requests header or param, then decide what downstream microservice cluster to forward the request. For example, based on client type, SG can reroute request to legacy service or new service target cluster.</li><li><strong>authn and authz</strong>: SG can inspect the security fields in request to ensure the request is from authenticated user, and they are authorized for the requested resource, otherwise 403 unauthorized error will be returned;</li><li><strong>logging and metrics</strong>: SG is a good place to collect the service call volume and latency info.</li></ol><h4>Is Service Gateway a Single Point of Failure?</h4><p>It could be, if not set up properly in the system.</p><p>We should place LB in front of a group of SGs to ensure the scalability, however, do not have LB sits in front of all microservice instances, as it then becomes the bottleneck.</p><p>Then configure SG to use Eureka(service discovery) to directe requests to certain service.</p><h4>Reverse Proxy and Zuul</h4><p>Reverse proxy sits between client and its target resource. Client has no visibility of microservice layout, and it only talks to the service gateway(Zuul). Zuul is responsible for relaying the client request to certain downstream service endpoint, based on routine rules. Such routine rules including:</p><ol><li><strong>Automated mapping via service discovery(Eureka)</strong>: Use the service id from client request section to lookup in Eureka. The client request is something like below, where <strong>localhost:5555</strong> is the Zuul gateway URL, and <strong>organizationservice</strong> is the service id: <a href="http://localhost:5555/organizationservice/v1/organizations/e254f8c-c442-4ebea82a-e2fc1d1ff78a"><em>http://localhost:5555/</em><strong><em>organizationservice</em></strong><em>/v1/organizations/e254f8c-c442-4ebea82a-e2fc1d1ff78a</em></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*gFekzUmDjD1eKLLH" /></figure><p>2. <strong>Manual mapping via service discovery(Eureka)</strong>; It’s similar to automated mapping, only difference is that you can specify a mapping in SG’s yml file when the service id in client request does not match the downstream Eureka registry. It can also add certain exclusion rules to prevent certain service routine. For example:</p><pre>zuul: <br> routes:     <br>   organizationservice: /organization/**</pre><p>3. <strong>status service URL mapping</strong>. We can also add static URL to achieve static routing for certain service, such as:</p><pre>zuul:   <br>  routes:     <br>    licensestatic:      <br>      path: /licensestatic/**      <br>      url: <a href="http://licenseservice-static:8081/">http://licenseservice-static:8081</a></pre><p>Or more advanced, you can wrap the service hosts as a LB group using Ribbon:</p><pre>zuul:   <br>  routes:     <br>      licensestatic:       <br>        path: /licensestatic/**       <br>        serviceId: licensestatic <br>  ribbon:   <br>    eureka:     <br>      enabled: false #disable Eureka support in Ribbon <br>licensestatic:   <br>  ribbon:     <br>      listOfServers: <a href="http://licenseservice-static1:8081/">http://licenseservice-static1:8081</a>, <a href="http://licenseservice-static2:8082/">http://licenseservice-static2:8082</a></pre><h4>Filtering in Zuul</h4><p>Different types of filter are supported in Zuul, each filter type is acting at the different stage of request lifecycle. See below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*-i4zjJ2Euw9x4ja-" /></figure><ol><li><strong>Pre-filter:</strong> Acts before request reaching target server, it is usually used for intercepting the request and perform authz/authn process, or sanity check the request has expected header fields. A pre-filter cannot redirect the user to a different endpoint or service.</li><li><strong>Post-filter</strong>: Acts when response is returned from service back to client. Usually it’s where the logging, auditing and error handling occurs, sometimes it’s also used to decorate the response, such as adding artificial fields when return response to client.</li><li><strong>Route-filter</strong>: Route filters can change the destination of where the service is heading. It’s to support certain ad-hoc routine, e.g. diverge a small volume of traffic to a different routine target.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vKgY035U3SkPH6wA" /></figure><p>Below is a comprehensive use case using different types of filters together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*zprbgKAErk6QqaHm" /></figure><h4>More Read</h4><p>How to add new field such as request UUID to RequestContext via pre-filter, and how to get this new field from httpServletRequest header, then pass it down to service call, by using UserContext and UserContextHolder. It also involves usage of ThreadLocal variable to store the UserContext:</p><blockquote>Store the UserContext in a ThreadLocal variable that is accessible in any method being invoked by the thread processing the user’s request.</blockquote><p>Write Medium in Markdown? Try <a href="https://markdium.dev/">Markdium</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ccbafd73532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<Spring Microservices in Action> Reading Notes]]></title>
            <link>https://medium.com/@yangli907/spring-microservices-in-action-reading-notes-6abd497fa969?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6abd497fa969</guid>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[hystrix]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 08:22:36 GMT</pubDate>
            <atom:updated>2020-02-23T04:38:18.964Z</atom:updated>
            <content:encoded><![CDATA[<h3>&lt;Spring Microservices in Action&gt; Reading Notes — Part 3</h3><h4>Configuration management and Service Discovery</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*j8ktVnyDEg5J9BD_" /></figure><h4>Why Configuration Management?</h4><p>If the application configuration is baked into the application code itself, every time we needs config change, the code needs to be recompiled, redeployed and/or restarted.</p><p>There are couple ways to solve it:</p><ol><li>Ensure the application is reading config from environment variables, where those variables are initiated when application started. Then whenever we need to update the configuration file, we can write an util runnable or API endpoint to reload the environment variables from file. Check out <a href="https://javabycode.com/java-core/java-io/how-to-update-properties-file-in-java.html">this post</a> on how to use org.apache.commons.configuration to load and reload such config from property file. However, this approach wouldn&#39;t work in large scale because we&#39;d need to manually trigger such reload process on all nodes.</li><li>Build a centralized configuration repository, and abstract the data access by exposing key-value pairs via REST-based JSON. Whenever application is starting, it’ll lookup the needed properties from the central config service. Compare to first approach, this is more scalable. We can choose different way to store the config, one typical practice is to use version control system to store and version the config files.</li></ol><h4>Key Requirement for Config Management System</h4><ol><li><strong>Segregate</strong> config data from application code;</li><li><strong>Abstract</strong> the config data access via REST API;</li><li><strong>Centralized</strong> config service to avoid scaling operation burden;</li><li>Achieve <strong>HA</strong> via data redundancy and failover setup.</li><li>Config data can be retrieved based on <strong>specific environment</strong>;</li><li>Notify application to <strong>refresh</strong> when config is updated.</li></ol><h4>Ways to implement Config Management System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*juCM3xb8d6brC7yS" /></figure><h4>Spring Cloud Configuration Server(SCCS)</h4><p>SCCS stores environment specific service config in FS or VCS, it’s preferable to use VCS as it’s easier to set up, otherwise you’ll need shared FS mount across servers, which is another operational burden.</p><p>(Details of how to set up SCCS and config file is hereby skipped. Will add if it’s considered useful)</p><p>The outcome of application service integration with SCCS is like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*6XWx2k2OU-TtTJtR" /></figure><p>When you request licensing service config for dev env, you will make a call to GET http://localhost:8888/licensingservice/dev, which returns the following config back (with callback):</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*rgQBFVfflRoROhRX" /></figure><h4>Integrate SCCS with Spring Application</h4><p>Once SCCS is up, we can define the cloud config property for client service application(e.g. <em>licensing service</em>), we can have below config bootstrap yml file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4560c7e93f7bb5447a39ea086a3c101e/href">https://medium.com/media/4560c7e93f7bb5447a39ea086a3c101e/href</a></iframe><p>When starting the microservice, we have the opportunity to override it with a different config host or environment name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fabb839c397ca551590f2222edd3d536/href">https://medium.com/media/fabb839c397ca551590f2222edd3d536/href</a></iframe><h4>Refresh properties using SCCS</h4><p>Spring application only loads property as environment variable from SCCS during service startup, we need to use a built-in @RefreshScope annotation at main application, so that /refresh endpoint can be used to reload the config.</p><pre>@SpringBootApplication<br>@RefreshScope<br>public class Application {<br>  public static void main(String[] args) {<br>    SpringApplication.run(Application.class, args);<br>  }<br>}</pre><h4>Storing sensitive property data</h4><p>We want to avoid saving sensitive data such as DB password etc. in FS or VCS, one workaround is to download JCE jar for encryption, add it to JAVA_HOME, then export ENCRYPT_KEY, afterwards we can use /encrypt endpoint of Spring service to encrypt the string, then store the property in format prefixed with {cypher} as below:</p><pre>spring.datasource.password:&quot;{cipher}<br>858201e10fe3c9513e1d28b33ff417a66e8c8411dcff3077c53cf53d8a1be360&quot;</pre><h4>Service Discovery</h4><h4>Overview</h4><p>Service discovery provided a mean to effectively decouple service consumers and service provider instances, without extra operational burden, such as load balancer registry management, hence enables quick scaling, resiliency and HA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*a8t9tTuVnFcttx0C" /></figure><h4>Issue with traditional DNS + LB approach</h4><p>In the traditional DNS + LB approach, service consumer first looks up DNS service to find the LB(<strong>F5</strong> or <strong>HAProxy</strong>), then LB find and return the target service instance’s address in routing table to client.</p><p>However, the registry in LB’s routing table is usually statically stored in centralized DB, and relies on registry management API or even manually maintained, which is apparently not scalable in distributed infrastructure with hundreds even thousands of nodes. (<strong>Management complexity</strong>)</p><p>Furthermore, the HA of such LB is implemented via an idle HA pair, only becomes active when master LB goes down. (<strong>Limited capacity due to single LB nature</strong>)</p><p>Lastly, the licensing cost for LB is associated with cluster size, it tended to be expensive when cluster becomes big. (<strong>Expensive</strong>)</p><h4>Cloud-based service discovery architecture</h4><p>The general concept of service discovery architecture is:</p><ol><li><strong>Service registration</strong> — upon service instance start up, it’ll register to service discovery instance with the following information:</li><li><strong>physical address</strong>,</li><li><strong>endpoint path</strong>(with port),</li><li><strong>service id</strong>, which is the key(usually integer) of the service, for example, 42 means auth service, 43 means user service ,etc. Each node under one service group will register with same service id.</li><li><strong>Client lookup</strong> — service consumer periodically contact service discovery host for service group info, and <strong>cache it locally</strong>. When it needs to call certain service, it’ll lookup local cache, apply certain LB algorithm(such as round-robin) to find target service instance. Other than periodical refresh, it also proactively invalidate local cache if it reaches unhealthy node, then instantly refresh the cache.</li><li><strong>Information sharing</strong> — service discovery instances are usually a group of nodes. Service instance only register its info to one service discovery node, and then this node will share the info among peers to propagate the info.</li><li><strong>Health monitoring</strong> — if a node is found as unhealthy, i.e. the heartbeat check failed, then the service discovery instance will mark it as bad node, eliminate from the service instance group.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*bOjsrVtPlreqOaoU" /></figure><p>Below diagram shows how the Ribbon is used to achieve client side load balancing with resiliency support:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*E0TL6pe5dbmma4kO" /></figure><h4>Implement Service Lookup</h4><p>In a nutshell, we can implement service lookup in three ways:</p><ol><li>Directly use DiscoveryClient to get a list of available service instance for service id from Eureka,</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*QfMhcpbv2oPHjESL" /></figure><ol><li>Leverage Ribbon-aware RestTemplate to perform the cache lookup mentioned earlier. The latter approach is more preferable as it uses cache for better performance and fault tolerance.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*0-hHgSl_1zzwSE0D" /></figure><ol><li>Or use Feign client to allow dynamically generate service proxy for target host, hiding the Ribbon/Eureka details:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*iNBabCghZOBFzWVf" /></figure><h4>Next Up</h4><p>Will start look into client resiliency with Hystrix.</p><p>Write Medium in Markdown? Try <a href="https://markdium.dev/">Markdium</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6abd497fa969" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<Spring Microservices in Action> Reading Notes]]></title>
            <link>https://medium.com/@yangli907/spring-microservices-in-action-reading-notes-e3e476bdbd78?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3e476bdbd78</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cloud-services]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 06:28:43 GMT</pubDate>
            <atom:updated>2020-02-23T04:37:22.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>&lt;Spring Microservices in Action&gt; Reading Notes — Part 2</h3><h4>Architecture</h4><h4>Design Microservice Architecture</h4><p>Key focus area of microservice architecture design:</p><ul><li>Decomposing the business problem</li><li>Establishing service granularity</li><li>Defining service interfaces</li></ul><h4>Decompose business problem</h4><p>We should not always think a single microservice can fulfill the entire transaction. More often than not, a single request/transaction need multiple microservices across different business domains.</p><p>We should analyze the product requirements, pay attention to the nouns to identify domains, and the verbs to identify the functionalities. For example, if we are to implement a booking service, we probably need to look up product info as well as customer info, then save a booking transaction. Therefore we’d need <strong>UserService</strong>, <strong>ProductService</strong> and <strong>BookingService</strong> to fulfill this requirement.</p><h4>Establish service granularity</h4><p>One gotcha here is how to ensure the right level of granularity for microservice components:</p><ul><li>If each service is too coarse-grained, then it’s like to take more responsibilities. It’ll likely have a large number of underlying tables, and the business logic to fulfill client requests in this microservice is expected to be excessively complex.</li><li>Typically a golden rule is to have no more than 5 tables for a single microservice</li><li>If service is too fine-grained, such that each microservice is only responsible for a single CRUD operation, then a whole lot of inter-service calls are needed to fulfill a single request, which in inefficient and hard to maintain.</li></ul><p>One example of the decomposed service structure with proper granularity is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*9cl_lNzsb3okL_uj" /></figure><h4>Design Service Interface</h4><p>Like typical API design, we should follow the below guidelines when defining the service interface:</p><ul><li>Use verb and entity to define the function of interface. i.e. Get/Put/Post/Delete for CRUD operation of certain entities on server, identified by resource identifier.</li><li>Define JSON for request and response contract;</li><li>Communicate result via HTTP status code.</li></ul><h4>Operating Microservice</h4><p>Once the microservice is implemented and ready to serve traffic, we need to manage certain operations to release the service with proper configuration. There are a few objectives on how to manage such operation, illustrated by below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*btgG4u7BCRXosxWL" /></figure><h4>Self-contained</h4><p>Microservice should be encapsulated as self-contained package in order to be independently deployable. It’s usually achieved by assembling service into a jar/war artifact, upload to image repo, and then wait for deployment platform to spin up new instances with such artifact running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*sP3VK9Qhr5KbLfKg" /></figure><h4>Configurable</h4><p>Once service is deployed, we want the application to be started with environment specific configuration, without any human intervention. A well developed microservice usually can be configured via centralized configuration service, and/or properties file such as YAML. When the configuration has changed, we need either 1) reboot the instance to reload the config, if it cannot be refreshed at runtime; or 2) force a re-read to fetch the new configuration from remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*8rx69rmlNtxyvHJg" /></figure><h4>Transparent to client</h4><p>Client should not have the need to know what underneath service instances/pools they are talking with. Therefore, it’s useful to introduce service registration and discovery mechanism, so that whenever the instance is updated, or new version of application is deployed, they can be automatically discoverable. Client only needs to set up the binding of service communication for the first time.</p><p>During the registration process, service instance will register its IP address(e.g 192.168.8.20) and service logical name(e.g product-service) to service discovery agent(such as <strong>Eureka</strong> server), then the application will send request against service discovery agent when it needs to talk to certain services. Based on the logical name and LB routing, the request will be sent to specific FQDN.</p><p>For example, when a microservice is deployed and started on a given server instance, it should automatically register itself in Eureka registry, and keep sending heartbeat to the central load balancer/router. If client or other microservice host needs to talk to it, they’ll send request to it via e.g GET http://localhost:8080/service-discovery/blahService/getProductInfo, then Eureka/Ribbon will route the request to next available blahService instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*pigHBVk2t4N_Ye9g" /></figure><p>To read more about service registration and discovery, check out <a href="https://spring.io/guides/gs/service-registration-and-discovery/">this guide</a>.</p><h4>Health monitoring</h4><p>As mentioned above, the microservice should implement a generic health check endpoint, such as http://localhost:8080/ping, so that central discovery server can keep checking the heartbeat of underlying service instances, and swap out those down nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*CGEDh_B7g7sqThA9" /></figure><p>Spring Boot supports such health check feature via Spring Actuator. Read more about it at <a href="https://spring.io/guides/gs/actuator-service/">this page</a>.</p><h4>Next up</h4><p>Next post will be about the configuration management of microservice. Below is a high level architecture on how such system looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*OferAXzj4izubAbp" /></figure><p>Write Medium in Markdown? Try <a href="https://markdium.dev/">Markdium</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3e476bdbd78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<Spring Microservices in Action> Reading Notes]]></title>
            <link>https://medium.com/@yangli907/spring-microservices-in-action-reading-notes-b74c8f541588?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b74c8f541588</guid>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 03:54:47 GMT</pubDate>
            <atom:updated>2020-02-23T04:36:51.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>&lt;Spring Microservices in Action&gt; Reading Notes — Part 1</h3><h4>Overview</h4><h4>Intro</h4><p>This series of posts is my written notes from book &lt;<a href="https://www.amazon.com/Spring-Microservices-Action-John-Carnell/dp/1617293989">Spring Microservices in Action</a>&gt;, unless otherwise declared, all the diagrams or code are referenced from the book.</p><h4>Why Microservice?</h4><p>In monolithic architecture world, the application needs to be deployed as a single unit of work. Different teams cannot rapidly iterate on their own cadence due to the need of rebuild, retest and redeploy for the entire application.</p><p>Microservice architecture solves this problem by decomposing large application to well-defined smaller components, unbundling these components into independent pieces, so that each piece can build, deploy and test without impact others. Often, each component has its own version controlled repository.</p><p>Microservice infrastructure has the following characteristics:</p><ul><li>Components break down based on function and responsibility, with clear boundary;</li><li>Each component can be independently deployable, a microservice itself is reusable across multiple multiple applications; (<em>my understanding is its data schema and interface design is agnostic to other microservices</em>.)</li><li>Service consumer and provider communicate via lightweighted protocol(REST/JSON, gRPC/proto, etc.), and each microservice’s underlying implementation is irrelevant;</li><li>Since responsibility of each microservice is well defined and independent, as long as teams agreed on the interface design and scaling requirement, different teams can iterate on one component without caring other team’s development.</li></ul><h4>Spring Boot, Spring Cloud and Microservice</h4><p>Originally, Spring is primarily used for dependency injection, it externalized the relationship of objects in application, and allow using annotation or xml configuration to manage the dependencies, and assemble different classes into the application.</p><p>Spring further evolved over the years to service as an alternative of J2EE. Compare to Spring, J2EE has more boilterplate and complicated structure, and it’s harder to configure due to its dependency with certain Java application server(<em>Oracle Weblogic AS, IBM Websphere AS, JBoss EAP, etc.</em>) which takes bigger effort to set up.</p><p>Spring Cloud is a suite which integrates many populate cloud-management microservice frameworks together, and can be easily integrated into the application via application and easy bootstrapping process. After the application is built, it can be easily deployed to either private or public cloud.</p><p>Below diagram shows a typical REST API endpoint workflow using Spring Boot (complied to conventional Jersey way of building REST services):</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*40FEQ-34UtaO2-OF" /></figure><p>Below code snippet demonstrates how easy it is to use annotation to wire these routing, mapping and parameter passing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Z9Yf96TYhTSNEB7T" /></figure><p>Above example shows what a typical microservice interface looks like. In short, the benefit of microservice architecture is:</p><blockquote>Small, Simple, and Decoupled Services = Scalable, Resilient, and Flexible Applications.</blockquote><h4>Cloud-based Microservice</h4><p>There are several outstanding benefits to host the microservices on cloud:</p><ul><li><strong>Elasticity</strong> — you can allocate “just enough” resource to support the service “at current scale”. When surged or dropped traffic is expected to happen or already happened, cloud can scale up or scale down cluster accordingly, thus avoid potential waste of computing resource, or even worse, service downtime.</li><li><strong>Scale by service</strong> — When you have different services with skewed RPS and computational intensity, cloud-based infrastructure allows you to allocate cluster size to each microservice component without impacting other components.</li><li><strong>Multi-colo</strong> — Cloud infra has multiple data center across the world, it’s crucial for disaster recovery via service redundancy.</li></ul><p>Below diagram shows main considerations when building a microservice based application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*FYsIBIHE8k7FmJu7" /></figure><h4>Coming Next</h4><p>Topic in next post will be around Core microservice development pattern, it’s mainly about basic microservice design, such as how to define service granularity, communication protocol, interface design, config management and event processing.</p><p>Below is a diagram for the lifecycle of these areas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*FPQZQx55Kd35XfaV" /></figure><p>Write Medium in Markdown? Try <a href="https://markdium.dev/">Markdium</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b74c8f541588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2019 Trip to Barcelona]]></title>
            <link>https://medium.com/@yangli907/2019-trip-to-barcelona-46e186d3ddb7?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e186d3ddb7</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[barcelona]]></category>
            <category><![CDATA[spain]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 08:25:59 GMT</pubDate>
            <atom:updated>2020-01-23T05:50:40.926Z</atom:updated>
            <content:encoded><![CDATA[<p>After staying two days in Paris, we flew to Barcelona, the second destination of our trip.</p><p>Being the most lively, energetic and vibrant city of the world, Barcelona is famous for its mouthwatering tapas, delicious sangria, unique building style and prolonged history, which attracts millions of tourists every year. We’ve had the fortune to explore this beautiful destination and surrounding area in four days, and decide to write up this blog post about our trip. See our blog of Paris trip written by <a href="https://medium.com/u/21d13a44b1f2">Youyang Hou</a> at <a href="https://medium.com/@youyanghou/%E8%A5%BF%E6%AC%A7%E8%A1%8C%E7%BA%AA-%E6%B3%95%E5%9B%BD%E5%B7%B4%E9%BB%8E-7e72d943ff45">this link</a>(in Chinese)</p><p>Don’t forget to drop a clap or share this blog post if you find it useful! :-)</p><h3>TL;DR — Our Full Trip Itinerary</h3><p>We used <a href="https://place.qyer.com/">https://place.qyer.com/</a> to plan our trip, and it automatically generated the full itinerary for us, how awesome it is! Our day-to-day point of interests list is as below, though we skipped some of them due to scheduling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*DS7bxpdq1gQc-lQWmwjjWg.png" /><figcaption>Our trip itinerary (it’s generated by planning tool)</figcaption></figure><h4>Attractions Map(based on our plan)</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.google.com%2Fmaps%2Fd%2Fembed%3Fmid%3D1RxLkLH4Bxgc1D5-3hIAma7eSLx3Kyybu%26hl%3Den_US&amp;url=https%3A%2F%2Fwww.google.com%2Fmaps%2Fd%2Fviewer%3Fmid%3D1RxLkLH4Bxgc1D5-3hIAma7eSLx3Kyybu%26hl%3Den_US&amp;image=https%3A%2F%2Fwww.google.com%2Fmaps%2Fd%2Fthumbnail%3Fmid%3D1RxLkLH4Bxgc1D5-3hIAma7eSLx3Kyybu%26hl%3Den_US&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="600" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/9714c9974aa216f53a2e08457ac9d7e6/href">https://medium.com/media/9714c9974aa216f53a2e08457ac9d7e6/href</a></iframe><h3>Before You Go</h3><h4>Transportation</h4><p>You don’t need to rend a car to get around. The public transportation is very well developed here, you can go anywhere by taxi, Uber or subway. We found subway is very convenient, we bought a 10-time punch card which is very handy.</p><h4>Hotel</h4><p>If you are first time visiting, highly recommend booking hotel near la Rambla street. For more recommendations on which neighborhood to stay, check out this <a href="https://misstourist.com/5-neighborhoods-to-stay-in-barcelona-and-best-hotels-recommendations-for-each-of-them/">blog post</a>.</p><h4>Phone Service</h4><p>If you don’t have international phone service, I recommend purchasing a SIM card with data plan as soon as you arrive, preferable at the airport. The card is relatively cheap(~$15 for a 4G-8G data plan with 100 mins phone call), you can choose Vodafone, Orange or Lycamobile, and it can be used in other European countries as well.</p><h4>And, look after your stuff!</h4><p>Pickpocketing is a thing here, look after your stuff and don’t put phone/wallet/passport in the pocket that can be easily accessed. <br>If you have a backpack, make sure don’t put valuables in there, or wear it in front instead. <br>Lastly, stay away from strangers who approach you to ask weird requests(ask for direction, help you take photos etc.), it’s likely part of their trick to catch your attention and steal your stuff.</p><h3><strong>Day 1: Arrival</strong></h3><h4>Hotel</h4><p>We booked <a href="https://www.tripadvisor.com/Hotel_Review-g187497-d237157-Reviews-Hotel_Gaudi-Barcelona_Catalonia.html">Hotel Gaudí</a> on la Rambla street, the center of <a href="https://www.tripadvisor.com/Attraction_Review-g187497-d190162-Reviews-Gothic_Quarter_Barri_Gotic-Barcelona_Catalonia.html">Gothic Quarter</a> which packs a whole lot of sightseeing attractions and decent Spanish restaurants, all within walking distance.</p><p>Don’t forget to ask about rooftop access of the hotel, where you can grab a drink and enjoy the amazing view of the city, especially during sunrise/sunset time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMXJPMqFZM8eNmO3WaEXvg.jpeg" /></figure><p>For more recommendations on which neighborhood to stay, check out this <a href="https://misstourist.com/5-neighborhoods-to-stay-in-barcelona-and-best-hotels-recommendations-for-each-of-them/">blog post</a>.</p><h4>Food</h4><p>There are plenty of great restaurants on la Rambla, you can always find any types of food within less than 10 mins of walk. However, worth noting that people typically have dinner late and restaurant usually opens from 7pm to late after midnight, and wait time for those populate places tended to be quite long.</p><p>We had our dinner at <a href="https://www.tripadvisor.com/Restaurant_Review-g187497-d3722162-Reviews-Taller_de_Tapas_Rambla_de_les_FLors-Barcelona_Catalonia.html">Taller de Tapas</a>, tried the local bear and chef recommended seafood paella, ham pasta and grilled octopus, it was absolutely amazing at a very reasonable price($40 for 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*dy0vkC7VqukTocCH.jpg" /></figure><h4>Activities</h4><p>It’s 9:30pm after we walked out the Tapa restaurant, and realized the busy time of the night had not even started. So we booked a Flamenco Dance show in a nearby club(<a href="https://www.tripadvisor.com/Attraction_Review-g187497-d244937-Reviews-Los_Tarantos-Barcelona_Catalonia.html">Los Tarantos</a>, which turned out to be the top rated Flamenco show there, lucky us! )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IfxIbzSjxkihyRKV.jpg" /></figure><h3>Day 2: A day of Gaudí’s legacy</h3><p>Antoni Gaudí is one of the most famous and creative architects of the world, his unique art style influenced many area including sculpture, interior design, exterior decoration and furniture innovation. Visiting Gaudí’s masterpiece is the highlight of our travel agenda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*g8wPId42-WUstl3S" /><figcaption>Antoni Gaudí (source: www.bdbarcelona.com)</figcaption></figure><h4>Sagrada Família</h4><p><strong>Sagrada Família</strong> is maybe the most famous WIP(work in progress) of the world. The process to build this “skyscraping” church spanned across three centuries and yet finished. It’s such a stylish building, each facade has its own theme, thousands of unique sculptures represents different religious meanings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*1URJ9MfiWmKS2UgrgskD7g.png" /><figcaption><strong>Sagrada Família at sunrise</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*QnwOIx8IB1-h-79pcaKXgQ.png" /><figcaption>Sculpture on one side of the church</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*C6IwRlNgywHGPwSk0Nr9-Q.png" /><figcaption>Sculpture on another side of the church</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYGa9Tsw7lE6ZGvzBzGWCA.png" /><figcaption>Top of the church from inside</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*8JnOtBSJfEFxoF9cB9lyXg.png" /><figcaption>Sagrada Familia from Plaza of Gaudi</figcaption></figure><p><strong>Visiting Tips:</strong></p><ul><li>To enter the church, highly recommend booking ticket online before your visit, otherwise you may need to wait in line for hours.</li><li>The best time of the day to visit is around noon or late afternoon before sunset, you’ll experience the magical light effect due to the sunlight cascaded through the stained glass around the church.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfsXOCdsZA_kBAnd0GY21g.png" /><figcaption>Colorful glass from the church inside</figcaption></figure><ul><li><strong>Photography tips: </strong><br>- Visit <a href="https://www.google.co.in/maps/place/Pla%C3%A7a+de+Gaud%C3%AD/@41.4041691,2.174962,18z/data=!4m12!1m6!3m5!1s0x0:0x9bd8aac21bc3c950!2sLa+Sagrada+Familia!8m2!3d41.4036299!4d2.1743558!3m4!1s0x12a4a2dcc089b11f:0xfc4047f9ddb104b7!8m2!3d41.4046223!4d2.1757738">Plaça de Gaudí</a> during sunrise/sunset to shoot the photo of church overview with pond reflection.<br>- Buy<a href="https://book.tickets-barcelona.org/book/7603/select?date=2020-01-20&amp;time=09%3A45%3A00"> upgraded ticket with tower access</a>, where you can shoot the spiral staircase scene</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*LsUNgREX7H4megrDIx1skA.png" /><figcaption>Spiral Staircase of Sagrada Família<strong>(source from Flickr, not my photo)</strong></figcaption></figure><h4>Hospital de Sant Pau</h4><p>Just about 10 mins walk from Sagrada Família, we arrived at another historical site - Hospital de Sant Pau. The hospital was built in 1401 and was a full service hospital until 2009. Nowadays, it’s a museum and cultural center open to tourists.</p><p>We didn’t end up going inside of the hospital this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82WgOUS64EuZ9_WiuUsXKg.png" /></figure><h4>Casa Batlló</h4><p>Casa Batlló is another masterpiece from Gaudí, where he showcased his Art Nouveau style interior and exterior decoration design. <br>Casa Batlló locates in the Eixample district of Barcelona. From outside, the colorful ceramic tiles are decorated in a wavy mosaic style.</p><p><strong>Admission</strong>: €24.50 online/€28.50 at door. <br><strong>Address</strong>: Passeig de Gràcia, 43.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*4roK-Jxq8aatsnRO.jpg" /><figcaption>Casa Batlló exterior (source from google, not my photo)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*-RZV9iOObN16OlhXEa2ryQ.png" /><figcaption>Hallway of Casa Batllo</figcaption></figure><h4>Park Güell and Gaudí House Museum</h4><p>After a 20 mins hilly hike, we arrived at the last destination of the day — Park Güell. The whole park located on a hill, and has a big plateau with overview of Barcelona. You’ll need to buy admission ticket to enter the plateau area and visit the cultural center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYAgHEdFZH4F08-eIaV4Yw.png" /><figcaption>Park Güell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*FAzBUGbsE6PHN_l4snBRIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TIMHPwsJq1ar8EMOyTCqw.png" /><figcaption>Gaudí’s bedroom in Gaudí House Museum</figcaption></figure><p><strong>Resource</strong>:<br>Link of ticket purchasing for <a href="https://parkguell.barcelona/">the park</a> and <a href="https://sagradafamilia.org/casa-museu-gaudi">the museum</a>.</p><h4>Other suggested places nearby</h4><ul><li>Casa Mira — another landmark building from Antoni Gaudí, it’s adjacent to Casa Batlló.</li></ul><h4>Food</h4><p>Highly recomment <a href="https://www.tripadvisor.com/Restaurant_Review-g187497-d11906544-Reviews-Bodega_Biarritz-Barcelona_Catalonia.html">Bodega Biarritz</a>, a top rated local tapas bar. They have a 2-person €30 surprise menu, where you’ll be served 8 dishes with drink. Yummy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l_yGLqhMK_Rmm9sd.jpg" /><figcaption>Tapas, lots of Tapas! And giant sangria! <a href="https://medium.com/u/21d13a44b1f2">Youyang Hou</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Jh6FwvxJ2PI8EFeHgmOmw.png" /></figure><h3>Day 3: Girona</h3><p>Onto the third day of our trip, we went outside of Barcelona city for a day tour at Girona and Pals. For top rated tour around Girona, you can check out <a href="https://www.tripadvisor.com/Attractions-g187499-Activities-c42-Girona_Province_of_Girona_Catalonia.html">this link</a>.</p><p>Girona is located around 60 miles from Barcelona. It has well-preserved historical city with its winding alleys, arches, towers and city walls from centuries ago. It’s also where Game of Thrones season 6 was shot, if you watched this season, you’ll find many scenes familiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*0FQ5xA5ekKV4YBpWbpsAeA.png" /><figcaption>GoT S6 scene(from Google)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*FatE9pkF8uU8Ghfg0RT55w.png" /><figcaption>Girona Cathedral</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*kCYV5kN1dL-wf6q6_KKDEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNMnDQeHfO7_ZvzOo7F-vQ.png" /></figure><p>Other than the landmark Girona Cathedral, the town is very walkable, it has some Jewish cultural museum, souvenir store and local farmer’s market, where you can easily spend a few hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67JUTPBhz3uStWXhZ0z6vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*OI1chiVlYyjy8GBz_4HoJQ.png" /><figcaption><a href="https://medium.com/u/21d13a44b1f2">Youyang Hou</a> at the path of “shame” atonement walk :D</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVV1HtO1YX-0n_jkwuvy0w.png" /><figcaption>Farmer’s market at Girona</figcaption></figure><h3>Day 3(cont’d): <strong>Village Medieval de Pals</strong></h3><p>After lunch, we took another 40mins drive towards Pals, a charming ancient village and historical site. As the name of the town suggested, everything here was from Medieval time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*2I2ToJfCnT4DvWH3HpBhqQ.png" /><figcaption>Alley in Pals</figcaption></figure><p>Every building and alley of this town is very well decorated in a bronze tone, and there are houses labeled in ancient characters denoting silversmith, outwear shop, potion store, etc., some people wear traditional old clothes, made me feel like in an RPG game lol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*UU-7jdo4efisZcDOpWGCwA.png" /><figcaption>Cactus, another cactus and <a href="https://medium.com/u/21d13a44b1f2">Youyang Hou</a> at Pals, Spain</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*TKuwucBijp3t8f1ivLF1RQ.png" /><figcaption>Church at Pals, Spain</figcaption></figure><p>The souvenir store here has lots of great little art crafts with cheap price, highly recommended to spend some time and check it out.</p><p>Last destination is to drive towards the seaside beach named <a href="https://www.google.com/maps/place/Platja+d&#39;En+Calau/@41.8883158,3.1821486,17z/data=!3m1!4b1!4m5!3m4!1s0x12ba535bb5dcb239:0x2773729e7f21d29!8m2!3d41.8883118!4d3.1843373">Platja d’En Calau</a>, where you can find lots of great seafood restaurant, and stunning ocean view like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BtLANLF-OsOD-3NRrTVTg.png" /><figcaption>View from <a href="https://www.google.com/maps/place/Platja+d&#39;En+Calau/@41.8883158,3.1821486,17z/data=!3m1!4b1!4m5!3m4!1s0x12ba535bb5dcb239:0x2773729e7f21d29!8m2!3d41.8883118!4d3.1843373">Platja d’En Calau</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RcAx-p2HF_xIHX4_" /><figcaption>with <a href="https://medium.com/u/21d13a44b1f2">Youyang Hou</a> at <a href="https://www.google.com/maps/place/Platja+d&#39;En+Calau/@41.8883158,3.1821486,17z/data=!3m1!4b1!4m5!3m4!1s0x12ba535bb5dcb239:0x2773729e7f21d29!8m2!3d41.8883118!4d3.1843373">Platja d’En Calau</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*uO-iQpRBEN3r3VqW" /><figcaption>View from <a href="https://www.google.com/maps/place/Platja+d&#39;En+Calau/@41.8883158,3.1821486,17z/data=!3m1!4b1!4m5!3m4!1s0x12ba535bb5dcb239:0x2773729e7f21d29!8m2!3d41.8883118!4d3.1843373">Platja d’En Calau</a></figcaption></figure><h4>Day 3(cont’d): Mercado de La Boqueria</h4><p>Driving back to Barcelona, it’s already dinner time. We decided to walk to <a href="https://goo.gl/maps/AxmWVqKfW9AkDnKK9">Mercado de La Boqueri</a>, the largest public indoor food market, and <strong>you don’t wanna miss it and be there early(it closes at 8:30pm)</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*px3qxZCIcojIm8WE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r62568OKMmi8S8KE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7dGhaWYg53I1uu6J" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*D9-SUQTR9wEtC7Kg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drE4NzdhecwpPuyWZo9mxA.png" /></figure><p>To wrap up the day, we went to the show club next to <a href="https://www.tripadvisor.com/Attraction_Review-g187497-d244937-Reviews-Los_Tarantos-Barcelona_Catalonia.html">Los Tarantos</a> for a Tango performance.</p><h3>Day 4: Barcelona Cathedral and Museums</h3><p>It’s the last day of our stay at Barcelona, we planned a few historical site sightseeing, mainly on Barcelona Cathedral, several museums, and passed through a few plazas.</p><h4>Barcelona Cathedral</h4><p>Barcelona Cathedral located in the Gothic Quarter, its full name is “Cathedral of the Holy Cross and Saint Eulalia”. This massive Gothic style church was built in 14th century.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*DsZVg9KDuCQ50AsJhruw9A.png" /><figcaption>Front facade of Barcelona Cathedral</figcaption></figure><p>There were a lot of street performers on the plaza, I shot a small video on a few scenes around this area:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD25qufpTsM4%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD25qufpTsM4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD25qufpTsM4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2143c8df3b7643e91a4956c6dbdda30/href">https://medium.com/media/d2143c8df3b7643e91a4956c6dbdda30/href</a></iframe><p>Unlike other indoor oriented church, this cathedral actually has a huge front yard with many resident animals(goose, chicken, sheep, etc.), each species represents special religious meanings. For example, according to <a href="https://theculturetrip.com/europe/spain/articles/11-things-you-didnt-know-about-barcelonas-cathedral/">this post</a>,</p><blockquote>“ 13 geese which represent the fact that Saint Eulalia is believed to have been just 13 when she died. The geese can often be seen bathing in the <em>Font de les Oques</em> (or ‘Well of the Geese’) which is adorned with a statue of Saint George (patron saint of Catalonia) slaying the dragon.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCHeTZGmtZNI9ooWK9yf7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*N7zSVvNMWUe8zVbT419Wzw.png" /><figcaption>Barcelona Cathedral from inside</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*dMrtoR0qpJvSzVSnJ-yDDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*5ARWANZo5r8QmjcLoo7mew.png" /><figcaption>Barcelona Cathedral from inside</figcaption></figure><h4>Port Olimpic</h4><p>We picked this place as our sunset spot, and it was absolutely amazing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksGbH2PT8aRAHRrVW0YOMA.png" /><figcaption>Where is the Professor? (la casa de papel is apparently super popular here)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPfdqGMeXIv0X2R8xnH3lA.png" /><figcaption>Barceloneta Beach at sunset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4uBWIuTRnucyQa5V6_Zcg.png" /><figcaption>Barceloneta Beach at sunset</figcaption></figure><p>And it wraps up our Barcelona trip, it was a great journey, and I’m sure we’ll come back to explore the other gems of this beautiful city!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*-GLOX3qm__VmOGtm-_zxwA.png" /></figure><p>Next up, I’ll write another post about our trip to Madrid and Paris. Again, drop a clap or share it if you find this blog useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e186d3ddb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring-Cloud and Microservice(Part 3)]]></title>
            <link>https://medium.com/@yangli907/spring-cloud-and-microservice-part-3-d8b6361723c3?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b6361723c3</guid>
            <category><![CDATA[hystrix]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 22:52:52 GMT</pubDate>
            <atom:updated>2019-08-27T22:52:52.594Z</atom:updated>
            <content:encoded><![CDATA[<h4>API Gateway and Fault Tolerance</h4><h4>API Gateway</h4><p>API Gateway is a component to perform gateway handling for any API requests against microservices. Such handling including:</p><ul><li>authz and authn, security</li><li>rate limiting, , fault tolerance</li><li>service aggregation</li></ul><h4>Setting up API Gateway using Zulu</h4><p>Define a new Spring-Cloud project with Zuul dependency, annotate the main application with @@EnableZuulProxy (see TODO below) and @EnableDiscoveryClient. Then create a new filter for request intercept and handling such as logging. The filter needs to extend the ZuulFilter class with various methods. In this case we simply add logging to the incoming request:</p><pre>@Component<br>public class ZuulLoggingFilter extends ZuulFilter {<br><br>    private Logger logger = LoggerFactory.getLogger(ZuulLoggingFilter.class);<br><br>    @Override<br>    public String filterType() {<br>        return &quot;pre&quot;;<br>    }<br><br>    @Override<br>    public int filterOrder() {<br>        return 0;<br>    }<br><br>    @Override<br>    public boolean shouldFilter() {<br>        return true;<br>    }<br><br>    @Override<br>    public Object run() throws ZuulException {<br>        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();<br>        logger.info(&quot;request -&gt; {} request uri -&gt; {}&quot;, request, request.getRequestURI());<br><br>        return null;<br>    }<br>}</pre><p>Next important step is to specify the Eureka naming server address in Zuul property, this is to enable Zuul to look up certain services to proxy the requests:</p><pre>spring.application.name=netflix-zuul-api-gateway<br>server.port=8765<br>eureka.client.service-url.default-zone=http://localhost:8761/eureka</pre><p>Afterwards, we should be able to route the normal microservice requests though Zuul API gateway, with the following convention:</p><pre>BEFORE:<br>http://localhost:8000/currency-exchange/from/USD/to/CNY<br>AFTER:<br>http://localhost:8765/currency-exchange-service/currency-exchange/from/USD/to/CNY</pre><p>The console also shows the added logging via filter:</p><pre>2019-08-26 23:37:01.944  INFO 49311 --- [nio-8765-exec-3] c.y.s.n.ZuulLoggingFilter                : request -&gt; org.springframework.cloud.netflix.zuul.filters.pre.Servlet30RequestWrapper@6aae4993 request uri -&gt; /currency-exchange-service/currency-exchange/from/USD/to/CNY</pre><ul><li>[ ] Understand forward proxy and reverse proxy; (See <a href="https://www.cloudflare.com/learning/cdn/glossary/reverse-proxy/">What Is A Reverse Proxy? Proxy Servers Explained | Cloudflare</a>)</li><li>[ ] Understand the difference between @EnableZuulProxy and @EnableZuulServer, where the former has built-in reverse proxy filter for request routing</li></ul><h4>Microservice communication via Zuul Gateway</h4><p>As mentioned above, when sending request to Zuul API gateway, it fetches the remote service instance info from Eureka and delegate the request sending. We can simply update the Feign endpoint to Zuul gateway, and change the api endpoint to include the target service name prefix:</p><pre>//@FeignClient(name=&quot;currency-exchange-service&quot;)<br>@FeignClient(name=&quot;netflix-zuul-api-gateway&quot;)<br>@RibbonClient(name=&quot;currency-exchange-service&quot;)<br>public interface CurrencyConversionServiceProxy {<br>//    @GetMapping(&quot;/currency-exchange/from/{from}/to/{to}&quot;)<br>    @GetMapping(&quot;/currency-exchange-service/currency-exchange/from/{from}/to/{to}&quot;)<br>    CurrencyConversionResult getExchangeValue(@PathVariable(&quot;from&quot;) String from, @PathVariable(&quot;to&quot;) String to);<br>}</pre><h4>Circuit Breaker using Hystrix</h4><p>When a certain API endpoint does not return expected result and we want to have a safe fallback, we can use Hystrix to achieve it. The configuration is quite straightforward:</p><ol><li>Adding Hystrix gradle dependency: implementation ‘org.springframework.cloud:spring-cloud-starter-netflix-hystrix’</li><li>Annotate the main application class to enable Hystrix</li></ol><pre>@EnableHystrix<br>public class CurrencyExchangeApplication {<br>...</pre><p>3. Annotate the service endpoint to specify the fallback method name:</p><pre>@GetMapping(&quot;/example-error-service&quot;)<br>@HystrixCommand(fallbackMethod = &quot;getFallbackResponse&quot;)<br>public ExchangeValue getExampleErrorService() {<br>    throw new RuntimeException();<br>}<br><br>public ExchangeValue getFallbackResponse() {<br>    return new ExchangeValue(&quot;CNY&quot;, &quot;USD&quot;, BigDecimal.valueOf(999));<br>}</pre><p>4. Afterward, we should be able to see expected fallback behavior if original target method is returning error.</p><h4>Spring Cloud Bus, Zipkin and Spring Cloud Sleuth</h4><ul><li>[ ] TODO.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b6361723c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring-Cloud and Microservice(Part 2)]]></title>
            <link>https://medium.com/@yangli907/spring-cloud-and-microservice-part-2-fadbbe52ebd?source=rss-7677e5c0e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fadbbe52ebd</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[netflix]]></category>
            <dc:creator><![CDATA[Yang(Bruce) Li]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 05:45:20 GMT</pubDate>
            <atom:updated>2019-08-27T05:46:20.093Z</atom:updated>
            <content:encoded><![CDATA[<h4>Microservice Communication</h4><h3>Calling other microservice endpoint</h3><h4>Naive Approach</h4><p>If we have a currency conversion microservice, which needs to talk to another microservice to get latest exchange info, we need to have a way to invoke remote service and process the response. One way to achieve this is to use RestTemplate().getForEntity() method as below:</p><pre>@RestController<br>public class CurrencyConversionController {<br><br>    @GetMapping(&quot;/currency-conversion/{from}/to/{to}/amount/{amount}&quot;)<br>    public CurrencyConversionResult convertCurrency(@PathVariable String from,<br>                                                    @PathVariable String to,<br>                                                    @PathVariable BigDecimal amount) {<br>        Map conversionServiceParams = new HashMap&lt;&gt;();<br><br>        conversionServiceParams.put(&quot;from&quot;, from);<br>        conversionServiceParams.put(&quot;to&quot;, to);<br>        conversionServiceParams.put(&quot;amount&quot;, amount.toPlainString());<br><br>        ResponseEntity response<br>            = new RestTemplate().getForEntity(&quot;http://localhost:8000/currency-exchange/from/{from}/to/{to}&quot;,<br>            CurrencyConversionResult.class,<br>            conversionServiceParams);<br><br>        CurrencyConversionResult result = response.getBody();<br><br>        return new CurrencyConversionResult(from, to, amount, result.getRate(), result.getRate().multiply(amount));<br>    }<br>}</pre><p>however, as can see it’s pretty cumbersome to construct the request param as a map, and extract the needed info from returning response. We can leverage Feign http client with annotation to achieve the needs with cleaner code.</p><h4>Using Feign</h4><p>Feign is a wrapped version of HTTP client, which allows using annotation based configuration to call remote service endpoints.</p><p>First add Feign into Gradle dependency in the client side microservice(currency conversion service).</p><pre>+ implementation &#39;org.springframework.cloud:spring-cloud-starter-openfeign&#39;</pre><p>Then define a proxy in the client code, which mimic exactly the same interface as target service controller implementation, annotate with application name and service host:</p><pre>@FeignClient(name=&quot;currency-exchange-service&quot;, url=&quot;localhost:8000&quot;)<br>public interface CurrencyConversionServiceProxy {<br>    @GetMapping(&quot;/currency-exchange/from/{from}/to/{to}&quot;)<br>    CurrencyConversionResult getExchangeValue(@PathVariable(&quot;from&quot;) String from, @PathVariable(&quot;to&quot;) String to);<br>}</pre><p>We’ll need to further annotate the application class to declare it’s enabling Feign client:</p><pre>@SpringBootApplication<br>@EnableFeignClients(&quot;com.yangli907.springcloud.currencyconversion&quot;)<br>public class CurrencyConversionApplication {<br><br>	public static void main(String[] args) {<br>		SpringApplication.run(CurrencyConversionApplication.class, args);<br>	}<br>}</pre><p>Lastly, inject the proxy in controller class, and it should be ready to go:</p><pre>@Autowired<br>private final CurrencyConversionServiceProxy conversionServiceProxy;<br><br>...<br>CurrencyConversionResult result = conversionServiceProxy.getExchangeValue(from, to);</pre><h3>Client side load balancing using Ribbon</h3><p>By using Ribbon, client can be configured to speak with certain list of application servers for certain microservices. For example, in the currency conversion service, it talks with a pool of currency exchange service servers, each with different port. In this case, we can remove the URL section of @<strong>FeignClient</strong> annotation, then add a new @<strong>RibbonClient</strong> annotation with same target microservice name. put the list of target service server address in configuration with format {service_name}.ribbon.listOfServers For example, in the proxy class implementation, add below:</p><pre>//@FeignClient(name=&quot;currency-exchange-service&quot;, url=&quot;localhost:8000&quot;)<br>@FeignClient(name=&quot;currency-exchange-service&quot;)<br>@RibbonClient(name=&quot;currency-exchange-service&quot;)<br>public interface CurrencyConversionServiceProxy {<br>    @GetMapping(&quot;/currency-exchange/from/{from}/to/{to}&quot;)<br>    CurrencyConversionResult getExchangeValue(@PathVariable(&quot;from&quot;) String from, @PathVariable(&quot;to&quot;) String to);<br>}</pre><p>The application property file changes is as the following:</p><pre>currency-exchange-service.ribbon.listOfServers=http://localhost:8001,http://localhost:8000</pre><p>After bouncing the target microservice servers in different ports(8000 and 8001), now we can see the conversion service is selectively talking to both instances of exchange service.</p><h3>Naming Server using Eureka</h3><p>It’s not feasible in real project when number of service instances are large and dynamic. In such case, we need a better way to manage the service instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*z2hX9P-JWT8S7hWlEy43PQ.png" /></figure><p>With Eureka, it manages the instances for each service application, so that inter-service communication does not need to know other service’s exact host info, just need to check with Eureka for the registered service application to get needed instances info.</p><h4>Setting up Eureka</h4><p>We need to create a new microservice served as Eureka naming server, so that other applications will talk to it for instance host lookup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*6bggpnUXofOOSYCGMO9IeA.png" /></figure><p>In its main application, annotate the class with @EnableEurekaServer as below:</p><pre>@SpringBootApplication<br>@EnableEurekaServer<br>public class NetflixEurekaNamingServerApplication {<br>	public static void main(String[] args) {<br>		SpringApplication.run(NetflixEurekaNamingServerApplication.class, args);<br>	}<br>}</pre><p>Finally define a few application properties such as application name and port config:</p><pre>spring.application.name=netflix-eureka-naming-server<br>server.port=8761<br>eureka.client.register-with-eureka=false<br>eureka.client.fetch-registry=false</pre><h4>Configure clients to talk with Eureka naming server</h4><p>In currency exchange/conversion services, add the following dependency to enable Eureka client:</p><pre>implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-client&#39;</pre><p>Then add @EnableDiscoveryClient annotation in client app main class, so that it speaks to naming server to lookup host info of target services, instead of using the hard-coded “listOfServers” attributes.</p><pre>@SpringBootApplication<br>@EnableFeignClients(&quot;com.yangli907.springcloud.currencyconversion&quot;)<br>@EnableDiscoveryClient<br>public class CurrencyConversionApplication {<br>	public static void main(String[] args) {<br>		SpringApplication.run(CurrencyConversionApplication.class, args);<br>	}<br>}</pre><p>Once the server is up, we can safely remove the previously defined ribbon.listOfServers property, and we can view the Eureka app running on http://localhost:8761, with Eureka clients(currency exchange and conversion services) listed as application instances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP7f8xJZETsVbqLrBc6QIw.png" /></figure><p>Whenever a service request is received, the app will consult Eureka naming server for the instance info.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fadbbe52ebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>