<?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 Kamil Berdychowski on Medium]]></title>
        <description><![CDATA[Stories by Kamil Berdychowski on Medium]]></description>
        <link>https://medium.com/@kamil.berdychowski?source=rss-1c5b85f80a13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GUndKSgs2pu4zHlf.</url>
            <title>Stories by Kamil Berdychowski on Medium</title>
            <link>https://medium.com/@kamil.berdychowski?source=rss-1c5b85f80a13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:24:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kamil.berdychowski/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[Load testing with Gatling.io]]></title>
            <link>https://medium.com/pragmatists/load-testing-with-gatling-io-2a128fccfb3e?source=rss-1c5b85f80a13------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a128fccfb3e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Kamil Berdychowski]]></dc:creator>
            <pubDate>Wed, 08 Aug 2018 12:43:35 GMT</pubDate>
            <atom:updated>2020-01-16T08:27:49.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqdVvOcIVB5BFGuRZ-mDlA.jpeg" /></figure><h3>Performance testing</h3><p>What do you do when you want to check the system to see how it can perform, respond and scale under some simulated traffic? You can prepare performance tests.</p><p>There are many different types of metric that you may want to check and a range of tests that you can execute, for example:</p><ul><li>Load testing — checking how well a system performs under expected traffic generated by virtual users</li><li>Stress testing — checking upper limits of system capacity</li><li>Soak testing — checking how a system behaves after long period of usage by virtual users</li><li>Configuration testing — how changes made to parts of the system influence its responsiveness</li></ul><p>and many more tests that can simulate different scenarios. I’ll concentrate on load tests.</p><h3>Load tests</h3><p>Load testing is part of performance testing. It is designed to check how the system behaves under concurrent load of virtual users. As a result, you will have some metrics that describe how the system is performing. For example, if you are testing a REST API, you will know average response times of called endpoints. The tricky part of load testing is to get information about bottlenecks. Unless you add more monitoring and run different kinds of tests, you won’t know if the cause of potential problems is a database, code, hardware or network layer. However, load tests should answer the question of whether the system can handle the desired load and how it can scale</p><p>There are different tools that can be used to create load tests. JMeter and SoapUI are the most popular. In this article, I would like to introduce you to <a href="https://gatling.io/">Gatling</a>. In Gatling, tests are written in Scala. It uses <a href="https://akka.io/">Akka</a> actors to be able to efficiently execute the prepared simulation and scale it to the desired load. It also uses the concept of session to maintain state between calls.</p><h3>The plan</h3><p>I want to create a simple load test. I’m going to use<a href="https://jsonplaceholder.typicode.com/"> Jsonplaceholder</a> as the server that I want to check.</p><p>We will simulate a user who is browsing through some posts. He will open some of them, read comments and add comments of his own.</p><p>In order to start, we will need Java 8, as Gatling supports only this version, and Gatling binary that you can find here:<a href="https://gatling.io/download/"> https://gatling.io/download/</a>. I’ve created a Java project with dependency to Gatling which contains my scenario. You can find the project here <a href="https://github.com/antusus/gatling-posts">https://github.com/antusus/gatling-posts</a>.</p><h3>First simulation</h3><p>A test in Gatling is called a simulation. Extending Simulation class will give us access to tools needed to set up and execute tests. It will allow us to define actions, virtual users and the scenario that will be executed.</p><p>The whole code is in com.pragmatists.gatling.InitialSimulation and you can find it <a href="https://github.com/antusus/gatling-posts/blob/master/src/main/scala/com/pragmatists/gatling/InitialSimulation.scala">here</a>.</p><p>The most important part is calling the <strong>exec</strong> function on scenario.</p><pre><strong>val </strong><em>scn</em>: ScenarioBuilder = scenario(<strong>&quot;Initial Scenario&quot;</strong>)<br>  .exec(http(<strong>&quot;Get all posts&quot;</strong>)<br>  .get(<strong>&quot;/posts&quot;</strong>))</pre><p>Exec is using actions, that in most cases are requests. I’m testing REST API so I’ll be using HTTP requests. For the first step, I’m calling GET on /posts path. Gatling will automatically verify if the request is successful (response code is 2XX or 304). The name &quot;Get all posts&quot; defined in http creation will be shown in the report generated after successful execution.</p><p>I’m configuring HTTP protocol</p><pre><strong>val </strong><em>httpConf </em>= http<br>  .baseURL(<strong>&quot;https://jsonplaceholder.typicode.com&quot;</strong>)<br>  .acceptHeader(<strong>&quot;application/json&quot;</strong>)</pre><p>I’m executing requests against one API, so I’ve specified baseUrl. All requests that will not be an absolute http path will use baseUrl and the relative path defined in request. There are many options to configure in HTTP protocol and all are defined in the <a href="https://gatling.io/docs/current/http/">documentation</a>. I’ve set default options which specifies that I want the API to respond with JSON.</p><p>With scenario and protocol defined, I can set up the simulation.</p><pre>setUp(<br>  <em>scn</em>.inject(atOnceUsers(1))<br>).protocols(<em>httpConf</em>)</pre><p>I’m defining users. Right now, I’ll use just one user and later, we will have a look at how to define more interesting load strategies.</p><p>The last thing is to execute Gatling. If you applied configuration changes defined in the Github project, you can execute:</p><pre>./bin/gatling.sh -s com.pragmatists.gatling.InitialSimulation</pre><p>Gatling will run and should produce a report that will look like this:</p><pre>====================================================================<br>2018-07-20 17:15:48                                       1s elapsed<br>---- Requests ------------------------------------------------------<br>&gt; Global                                       (OK=1      KO=0     )<br>&gt; Get all posts                                (OK=1      KO=0     )</pre><pre>---- Initial Scenario ----------------------------------------------<br>[##############################################################]100%<br>          waiting: 0      / active: 0      / done:1<br>====================================================================</pre><p>There will be also a link to the generated report. We will have a look at it later. For now, I can see that there was one successful request OK=1 and no failures KO=0.</p><h3>Using session to maintain state</h3><p>In this part, I’m going to get posts and put them into session, so that we can later extract IDs and view some of them. The session concept is nicely explained in <a href="https://gatling.io/docs/current/session/session_api/#concept">here</a>. It’s a message that is exchanged between scenario steps, that are executed by Akka actors. It is a Map[String, Any] (where Any is similar to Object in Java). A session belongs to a virtual user, so that each user data is separated. You can add data to a session using feeders or extract values from requests.</p><p>The code can be found in com.pragmatists.gatling.DefaultSimulation and you can find the file <a href="https://github.com/antusus/gatling-posts/blob/master/src/main/scala/com/pragmatists/gatling/DefaultSimulation.scala">here</a>.</p><p>I’ll start with getting all posts:</p><pre>exec(<br>  http(<strong>&quot;Get all posts&quot;</strong>)<br>    .get(<strong>&quot;/posts&quot;</strong>)<br>    .check(jsonPath(<strong>&quot;$[*]&quot;</strong>)<br>      .ofType[Map[String, Any]]<br>      .findAll<br>      .saveAs(<strong>&quot;posts&quot;</strong>))<br>)</pre><p>You can see that after getting posts, I’m converting the response into a map. Calling saveAs will store posts in the session of one virtual user. I can use it later. To read data from the session, you can use expression language or session expression:</p><pre>exec((session: Session) =&gt; {<br><em>  </em><strong>val </strong>postsMap = session(<strong>&quot;posts&quot;</strong>).as[Vector[Map[String, Any]]]<br>  println(&quot;============ Sample post from list ============&quot;<br>  <em>println</em>(postsMap(0))<br>  session<br>})</pre><p>This is a session expression. It takes the session and it <strong>must return it</strong>. You can modify the session, but remember that it is immutable, so any modification will return a new session object. I’m getting all posts from the session, converting them and I’ll print the first post. After running the simulation, I’ll see:</p><pre>============ Sample post from list ============<br>Map(<br>userId -&gt; 1,<br>id -&gt; 1,<br>title -&gt; sunt aut ...,<br>body -&gt; quia et suscipit...)</pre><p>Saving response parts in sessions and later printing them is a way of debugging with Gatling. Calling session(“posts”) will retrieve an optional object from the session stored under the key “posts”. Now when I have posts stored, it’s time to open some of them.</p><h3>Using Expression language with Session</h3><p>Gatling comes with a simple <a href="https://gatling.io/docs/2.3/session/expression_el/">expression language</a>. I’ll use it to access posts stored in a session in order to get a random post.</p><pre>exec(<br>  http(<strong>&quot;Get one post&quot;</strong>)<br>    .get(<strong>&quot;/posts/${posts.random().id}&quot;</strong>)<br>    .check(jsonPath(<strong>&quot;$.id&quot;</strong>).saveAs(<strong>&quot;one_post_id&quot;</strong>))<br>)</pre><p>The expression ${posts.random()} will return a random element from the indexed collection. Next, I know that the post is a map. To get ID of a post, I’ll need to call $posts.random().id. I’m storing the opened post ID in the session. Next, I’m going to simulate reading comments for the opened post:</p><pre>exec(<br>  http(<strong>&quot;Read comments of post [${one_post_id}]&quot;</strong>)<br>    .get(<strong>&quot;/posts/${one_post_id}/comments&quot;</strong>)<br>)</pre><p>I’m using the expression even in the http request name. It will be shown in the report as a separated entry. The last thing is to add a comment of my own.</p><h3>Using feeders to generate data</h3><p>Feeders can be used to generate data for virtual users and store them in the session. They can be generated on the fly, read from a file and other places. You can read about feeders <a href="https://gatling.io/docs/2.3/session/feeder/">here</a>. I’ll create a simple CSV file with some comments (you can find it in src/main/resources/feeders/comments.csv). I’ll define feeder:</p><pre><strong>val </strong><em>commentsFeeder </em>= separatedValues(<strong>“feeders/comments.csv”</strong>, <strong>‘#’</strong>)</pre><p>It will be a custom feeder with separation marked as “#” (I’m using # only for parser, so it won’t create more columns; I need only one column named body). Feeder is basically an Iterator[Map[String, T]]. My CVS file looks like this:</p><pre><strong>body<br>Lorem ipsum dolor amet...</strong></pre><p>The first row defines the keys of the map that will be created in feeder, while subsequent rows define values. I’ll add feeder to my scenario:</p><pre>feed(commentsFeeder)</pre><p>This step will add the <strong>same</strong> <strong>feeder</strong> for every virtual user. Every time the execution reaches this step (for different users), it will get a record from feeder and place values in the session. It is important to provide as many entries as users in the file.</p><p>In my example, the name of the session entry will be called body. To create a new comment using feeder:</p><pre>feed(commentsFeeder)<br>.exec(<br>  http(&quot;Add comment&quot;)<br>  .post(&quot;/posts/${one_post_id}/comments&quot;)<br>  .body(StringBody(<br>    &quot;&quot;&quot;{<br>    &quot;name&quot;: &quot;gatling&quot;,<br>    &quot;email&quot;: &quot;<a href="/service/mailto:gatling@test.pl">gatling@test.pl</a>&quot;,<br>    &quot;body&quot;: &quot;${body}&quot;<br>    }&quot;&quot;&quot;.stripMargin))<br>  .check(jsonPath(&quot;$.body&quot;).is(&quot;${body}&quot;))<br>)</pre><p>You can see that I’m using ${body} in the POST request to retrieve data from the session using expression language. I’m also validating with check that the newly created comment has body with a value that I specified.</p><p>I would like to simulate opening three posts and adding a comment to them. I’ll use repeat function for that:</p><pre>exec(repeat(3) {<br>  exec(<br>    http(<strong>&quot;Get one post&quot;</strong>)...<br>}</pre><p>For each iteration, I’ll open a random post, get its comments, and add one of my own.</p><p>What is missing here is simulating the user looking at a post and comments. To do that, I’ll add pause:</p><pre>pause(10 second, 17 seconds)</pre><p>Pause will suspend execution of a scenario. It accepts either a fixed value or a range. In the latter case, the pause time will be random, but in an enclosed range.</p><h3>Defining load pattern</h3><p>For now, I was using only one user. It’s time to change that and simulate some traffic. It’s done through injection and you can read more about it <a href="https://gatling.io/docs/2.3/general/simulation_setup/">here</a>. There are plenty of options there, for example:</p><ul><li>several users started at once — atOnceUsers</li><li>linear injection of number of users for some duration of time — rampUsers</li><li>users can be injected at a constant rate across time intervals, where the injection times are randomised — constantUsersPerSec</li><li>users can be injected from the starting rate to the target rate during intervals — rampUsersPerSec</li></ul><p>I’m going to simulate two users starting, with three new ones showing up at random intervals. I want the test to run for 3 minutes (3 minutes ignoring pauses; with added pauses on my machine, it took almost 5 minutes for the whole simulation to complete):</p><p>scn.inject(rampUsersPerSec(2) to(3) during(180 seconds) randomized)</p><h3>Reading the test report</h3><p>Right after running the simulation, I can see in the console some basic information about request count.</p><pre>---- Default Scenario ----------------------------------------------<br>[##############################################################]100%<br>          waiting: 0      / active: 0      / done:422<br>====================================================================</pre><pre>====================================================================<br>---- Global Information --------------------------------------------<br>&gt; request count                           4220 (OK=4220   KO=0     )<br>&gt; min response time                         44 (OK=44     KO=-     )<br>&gt; max response time                       4020 (OK=4020   KO=-     )<br>&gt; mean response time                       168 (OK=168    KO=-     )<br>&gt; std deviation                            255 (OK=255    KO=-     )<br>&gt; response time 50th percentile             54 (OK=54     KO=-     )<br>&gt; response time 75th percentile            265 (OK=265    KO=-     )<br>&gt; response time 95th percentile            444 (OK=444    KO=-     )<br>&gt; response time 99th percentile            713 (OK=713    KO=-     )<br>&gt; mean requests/sec                     14.552 (OK=14.552 KO=-     )<br>---- Response Time Distribution ------------------------------------<br>&gt; t &lt; 800 ms                                          4184 ( 99%)<br>&gt; 800 ms &lt; t &lt; 1200 ms                                  11 (  0%)<br>&gt; t &gt; 1200 ms                                           25 (  1%)<br>&gt; failed                                                 0 (  0%)<br>====================================================================</pre><p>There were 422 users. Each executed 10 requests. I can quickly spot if something went wrong. I can also see the distribution of response times in the response time ranges. Those ranges can be defined by you, and you can read more about reports <a href="https://gatling.io/docs/current/general/reports/">here</a>.</p><p>I’m going to have a look at the HTML report that is also generated. What is important is that you can store files with simulation details (simulation.log) and generate reports with configuration changes later. You can have a look at the report in the simulation_results folder that I’ve added to the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r8L67ZJX_G8jnf_thu3NA.png" /></figure><p>Here I can see more detailed information about response times. I can see that for 99% of users, the response time of Get all posts was below 268ms. The minimum response time for this endpoint was 185ms, and the maximum was 507ms. We can also see charts for:</p><ul><li>Active Users along the Simulation</li><li>Response Time Distribution</li><li>Response Time Percentiles over Time (OK)</li><li>Number of requests per second</li></ul><p>There are also the charts that do not aggregate information for all requests. They allow us to view details of a specific request. It turns out that Add comment was one that was very slow (in my try):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-kULRAXedqM0j5U6zTPcQ.png" /><figcaption>Response Time Percentiles over Time (OK) for “Add comment” requests</figcaption></figure><p>Now I can see that after 15:57:58, the response times started to degrade. If I had access to more logs, I could try and determine what is causing that. The best part is that I can rerun the test and check if this behaviour will reoccur.</p><h3>Summary</h3><p>I’ve created a simple scenario that simulates a user browsing through posts, opening a few of them and adding comments. This will allow me to run tests when required and use other measuring techniques to check where there’s a weak spot, to fix it, and check how the system is behaving then. I could extract the scenario to a separate file (or files) and create many simulations with different traffic. In my opinion, Gatling simplifies the creation of tests that depend on data returned from the system being tested. With Session and Expression language, it is easy to store and retrieve data. Feeders can be used to prepare inputs if random strings are not enough.</p><p>Gatling can also do much more. I was testing REST endpoint and verifying JSON responses. But you can also test HTML or JMS responses. There is also the potential for writing functional specs in Gatling or performing real-time monitoring and persisting reports.</p><p>Now you can add a new tool to your arsenal for performing load testing.</p><ul><li><a href="https://blog.pragmatists.com/unobvious-traps-of-spring-webflux-16924a0d76d5">Unobvious traps of Spring WebFlux</a></li><li><a href="https://blog.pragmatists.com/structuring-terraform-for-world-domination-208d097a0680">Structuring Terraform for World Domination</a></li><li><a href="https://blog.pragmatists.com/spring-events-and-transactions-be-cautious-bdb64cb49a95">Spring events and transactions — be cautious!</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fcad346%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fcad346%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d80464f9d5e7ee80526950431dd262/href">https://medium.com/media/e4d80464f9d5e7ee80526950431dd262/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a128fccfb3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatists/load-testing-with-gatling-io-2a128fccfb3e">Load testing with Gatling.io</a> was originally published in <a href="https://medium.com/pragmatists">Pragmatists</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How NOT to break miscroservices dependencies with Consumer-Driven Contracts]]></title>
            <link>https://medium.com/pragmatists/how-not-to-break-miscroservices-dependencies-with-consumer-driven-contracts-3f46fabd7f57?source=rss-1c5b85f80a13------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f46fabd7f57</guid>
            <category><![CDATA[cdc]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Kamil Berdychowski]]></dc:creator>
            <pubDate>Wed, 28 Jun 2017 11:02:53 GMT</pubDate>
            <atom:updated>2018-11-30T14:00:22.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImvFxAWPt_G5enbxP0tQeg.jpeg" /></figure><p>So you have adopted the microservice way of software development. You have your pipelines ready, monitoring is watching, load balancers are making sure your product is available 24/7. You have unit tests, integration tests, maybe even some acceptance tests. Everything is green! But suddenly a recent release makes FooService no longer aligned with BarService, which makes some part of your product broken. What happened? Someone removed a field in a response that he or she thought was not being used any more.</p><p>Can we make sure this will not happen again? Yes, we can. We can forbid any breaking changes to the API. Problem solved — right?</p><p>Imagine that FooService retrieves a field that is very expensive to calculate. Let’s say it requires running dedicated SQL query that uses a lot of resources. We would like to remove it from response.</p><p>We want to be able to modify our API.</p><h3>Consumer-Driven Contracts</h3><p>There are many solutions to this problem. I’ll concentrate on a specific one called Consumer-Driven Contracts. As far as I’m aware this pattern was introduced by Ian Robinson and you can read his article <a href="https://www.martinfowler.com/articles/consumerDrivenContracts.html">here</a>. CDC allows to:</p><ol><li>Express a business requirement in a form of a specification that is being consumed.</li><li>Understand how a change done to an API will influence other applications that are using it.</li></ol><p>In this pattern there is a <strong>provider</strong> of an API and a <strong>consumer</strong>. Consumer specifies a contract that describes how it will use API. Provider then can check if this contract is being fulfilled by his API. If the check will fail provider will know which contract is broken and which with consumer.</p><p>I’m currently working with a customer whose development teams are building microservices. They had similar problems of broken products caused by breaking change in the API. Some time ago they have adopted Consumer-Driven Contracts to specify every API interaction. Now problems can be detected during development phase. Let me show you a tool they use and hopefully you will investigate on your own how to use it with your own build pipeline.</p><h3>Our task</h3><p>Let’s see how this pattern will help us avoid the problem of removing a field from a response in an API. But before we start we will need a sample problem to tackle. Let’s assume we are writing an application to manage a company library. We know we want to present a list of books and that they will have: a title, author, release year and an id. We are going to use a client-server architecture. Our client will show books and we can say it will <strong>consume </strong>books that will be <strong>provided</strong> by some microservice. Let’s assume that both consumer and provider are being developed by <strong>different teams</strong> (CDC approach, however, is useful even if one team is working on both the consumer and the provider side of the service). Oh, and I’ll use Java and Spring Boot.</p><p>From the consumer perspective we want to express a business need of showing books. We will create a consumer-contract that will specify what we require from API provider. We also know that it should be consumable. A provider should be able to verify if the latest API satisfies contracts of all consumers. If at least one of the consumers’ contracts is broken, we have to be able to tell which part of API breaks which consumers. So how can we accomplish that?</p><p>I’m going to use <a href="https://github.com/pact-foundation/pact-specification">PACT</a> library. It allows you to create tests on the consumer side that can be verified with the provider. I’ll be using JVM flavor of this library but you can get it also for Ruby and .Net. Let’s skip the project configuration, as you can read about it <a href="https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-consumer-junit">here</a>. You will need a dependency on PACT library in both consumer and provider projects. I’ll be using Spring Boot to create consumer and provider applications.</p><h3>Creating consumer contract</h3><p>We’ll start by writing a special test on a consumer side. Why it is special? We have to run it to see, but first things first. We will start with creating a JUnit test that will use SpringRunner to execute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e81b2a16e97249b150374ed2ae54932b/href">https://medium.com/media/e81b2a16e97249b150374ed2ae54932b/href</a></iframe><p>In the consumer project we have BooksReader class. This is a service that will execute HTTP request to read all books from a provider. Let’s write a test for scenario of reading all books:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13b0719a577c85bedc48fb7c5bf21165/href">https://medium.com/media/13b0719a577c85bedc48fb7c5bf21165/href</a></iframe><p>This test is annotated by @PactVerification(&quot;books_provider&quot;) which defines this interaction as a contract with books_provider. In this test we are calling bookReader.all()and expect it to return some books. We then can verify the books’ attributes to have specific values. This will require to setup the data later, when we’re writing verification part in the consumer project. If you do not care for the data, but just want JSON to be correctly deserialized into your object, then you have to remove the specific assertions and use more generic ones (for example just assert amount of books returned). Now, how can we setup this HTTP interaction? PACT JVM has a mock HTTP provider which we’ll use to create our mock provider:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e0e896390b7b80dd8b8edac1d253e97/href">https://medium.com/media/3e0e896390b7b80dd8b8edac1d253e97/href</a></iframe><p>You can see that this provider has a name books_provider. PACT will allow us to define interactions with several providers. In our example we have only one.</p><p>We have defined the provider, also we have declared what consumer is expecting to get while reading all books. What is left is to setup the mock provider to return some data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/882ca5ab151c53b138edb3dfab625c66/href">https://medium.com/media/882ca5ab151c53b138edb3dfab625c66/href</a></iframe><p>Method annotated with @Pact(provider = “books_provider”, consumer = “books_consumer”) defines a contract between books_provider and books_consumer for interaction of <em>“Request to get all books”</em> when we know that <em>“there are books to read”</em>.</p><p>The given(“there are books to read”) allows us to ask framework to put application into a specific state, and we will use this later when configuring provider.</p><p>The uponReceiving(“Request to get all books”) names the interaction. Then path and method tells HTTP mock to respond on specific HTTP method on a specific URL when consumer executes request. This ends the “when” phase of a test (where you describe what is being executed).</p><p>The part willRespondWith() defines the response from the provider. The status specifies HTTP response code, and body will allow us to tell what our consumer expects to get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796130e5e88fe68f1226f778f711c841/href">https://medium.com/media/796130e5e88fe68f1226f778f711c841/href</a></iframe><p>What we have defined here, is a response that will contain array, named “books”, with 2 elements (books) inside. Each book will have 3 string attributes: id, title, author and one numeric attribute year. Values of those attributes match exactly the values you have seen in our initial test. With PACT you can specify exact values that must be returned by the mock, or it can generate sample values. You can also provide a regular expression which will be used to generate a matching value. PACT documentation provides examples for all typical usages. Just remember to adjust assertions accordingly (for example if you do not care about the data you can just verify type of an attribute).</p><p>So we have created a test. But there are chances you have written similar tests before, so what is so special about this one? When we execute it a JSON file will be generated with a name books_consumer-books_provider.json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69c4bec859c39a534e7a55975007f0aa/href">https://medium.com/media/69c4bec859c39a534e7a55975007f0aa/href</a></iframe><p>The file name represents which consumer and provider interactions are described here. All your tests for interactions between same consumer and producer will be appended in one file. This is also why naming an interaction is important — you can’t have duplicate names.</p><p>This JSON represents our unit test. It names the provider and the consumer (1 and 2). It declares a list of interactions (3). Interaction (3.1) has a description, a request and a response just like the unit test we just wrote. There is also information about a state (4) and some metadata used by PACT (5).</p><h3>Verify contract by provider</h3><p>Now that we have our contract in the JSON file, you are probably assuming that this should be consumed by a provider. And you are right. We will start with a test in the provider project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5be672d5b3fdecf23529ed525a2a3be6/href">https://medium.com/media/5be672d5b3fdecf23529ed525a2a3be6/href</a></iframe><p>This test is using PactRunner to execute. We can name the provider that will be defined in this test with @Provider(“books_provider”. We are also defining a folder in which JSON contracts are stored (@PactFolder). This will make PACT runner to read all contracts and execute those that are specified for the provider specified in this test. Next we need to define a target used for our test. Our provider is a REST endpoint. We need to define something that will execute requests against it and verify responses. This is achieved with a Target interface and there is a target prepared for HTTP communication:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95de50d43d03e234c2c22582766e931c/href">https://medium.com/media/95de50d43d03e234c2c22582766e931c/href</a></iframe><p>This target will be used by PACT to execute requests defined in contract. We will need to run our application on the same host, port and protocol as specified in the target.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66733eb1de25c10e22d5f6ea34fe4c34/href">https://medium.com/media/66733eb1de25c10e22d5f6ea34fe4c34/href</a></iframe><p>We have specified a state in our contract so we need to provide it (the given(“there are books to read”) part in the consumer test):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23ce5cb8e98d2076fa88299b4144b21/href">https://medium.com/media/f23ce5cb8e98d2076fa88299b4144b21/href</a></iframe><p>We have also defined a BooksRepository implementation just for this contract verification:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9b8af851c6d9263015672e468802f4/href">https://medium.com/media/0b9b8af851c6d9263015672e468802f4/href</a></iframe><p>All that is left is to check if this test passes:</p><pre>Verifying a pact between books_consumer and books_provider</pre><pre>Given there are books to read</pre><pre>Request to get all books<br></pre><pre>returns a response which</pre><pre>has status code 200 (OK)</pre><pre>has a matching body (OK)</pre><p>Now let’s remove the year field from response of getting all books and run verification test again:</p><pre>has a matching body (FAILED)</pre><pre>Failures:</pre><pre>0) Request to get all books returns a response which has a matching body</pre><pre>$.body.books.0 -&gt; Expected year=2007 but was missing</pre><p>And the test failed! The body that was expected by a consumer was not delivered by a provider. I’ve omitted a part of the log so it is easier to read. The test response clearly states that a book is missing a year field. If we had this verification used as a part of the test phase of our build process we would have an immediate feedback that we are breaking a contract.</p><p>So what should happen when a test fails? I’m assuming that there are two different teams involved. One is working on the provider application and the other one on the consumer. Those teams should now have a conversation about what could be done. And after agreeing on a solution the consumer<strong> </strong>should adjust the contract and then the provider will implement it. If there is only one team then at least they know early that there is a change that will have an impact on the product.</p><h3><strong>Summary</strong></h3><p>We have created a test in the consumer project that defines a contract between it and some provider. Next we have created a test on a provider side that will get all contracts and verify if they are fulfilled. This verifies JSON structure that is required by a consumer to deliver some business functionality. Provider can have multiple contracts with one or more consumers. If at any point API change will break any contract, provider will be notified about that during build process.</p><p>In the end we can change API and know who will be impacted by our changes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fcad346%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fcad346%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d80464f9d5e7ee80526950431dd262/href">https://medium.com/media/e4d80464f9d5e7ee80526950431dd262/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f46fabd7f57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatists/how-not-to-break-miscroservices-dependencies-with-consumer-driven-contracts-3f46fabd7f57">How NOT to break miscroservices dependencies with Consumer-Driven Contracts</a> was originally published in <a href="https://medium.com/pragmatists">Pragmatists</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Driven Design vs. anemic model. How do they differ?]]></title>
            <link>https://medium.com/pragmatists/domain-driven-design-vs-anemic-model-how-do-they-differ-ffdee9371a86?source=rss-1c5b85f80a13------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffdee9371a86</guid>
            <category><![CDATA[software-craftsmanship]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Kamil Berdychowski]]></dc:creator>
            <pubDate>Tue, 03 Jan 2017 12:55:57 GMT</pubDate>
            <atom:updated>2020-01-16T08:52:27.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUSXxNdxYFvWFcH6e-fDUg.jpeg" /></figure><p>Some time ago during one of our internal DDD learning group meeting I was wondering what is the best way to show differences between writing an application with an anemic model and application with applied concepts of DDD. I came up with a drawing which illustrates these two types of application.</p><figure><img alt="Anemic Domain Model vs DDD" src="https://cdn-images-1.medium.com/max/1024/0*kU-C5Y7F2UGEYGsV.jpg" /></figure><p>Comparison of a common layered application and application with DDD architecture.</p><h4>Anemic model and bulky services</h4><p>Anemic domain model is nothing more but entities represented by classes containing only data and connections to other entities. These classes lack of the business logic, which usually is placed in services, utils, helpers etc. This design (three layers shown on the left side of the picture) is the natural way we model classes responsible for business cases.</p><p>When we implement a specific functionality, we first talk about the classes which will be persisted. We call them entities. They are represented as the letter E in the graph on the picture above. These entities are in fact object-oriented representation for the database tables. In result, we don’t implement any business logic inside them. Their only role is to be mapped by some ORM to their database equivalents.</p><p>When our mapped entities are ready, next step is creating classes for reading and writing them. We end up with the DAO (Data Access Objects) layer. Usually, each of our entities represents separate business case, so the number of DAO classes match the number of entities. They do not contain any business logic. DAO classes are nothing more than tools for retrieving and persisting entities. We can use an existing framework to create them, ie. spring-data with hibernate underneath.</p><p>The last layer, above the DAO, is the quintessence of our implementation — Services. Services make use of DAO in order to implement the business logic for specific functionality. Regardless of the number of functionalities, a typical service always performs following operations: loads entities using DAO, modifies their state according to requirements and persists them. Such architecture has been described by Martin Fowler as a series of Transaction Scripts. The more complicated the functionality, the bigger number of operations in between loading and persisting. Often some services start to make use of the other services, resulting in growing in tons of code, but only in the services. Entities or DAO stay the same, unless we provide new fields for persisting.</p><p>DDD comes with totally different approach in terms of placing the code in layers.</p><h4>Rich model and thin services</h4><p>Common architecture with Domain Driven Design model is presented on the right side of the picture.</p><p>Take note of a layer of services which is much thinner than his equivalent in an anemic model. The reason is that the most of business logic is included in Aggregates, Entities and Value Objects. In the services we put only operations working on many areas of the domain and logically fitting to none of these.</p><p>The domain layer has more types of objects. There are the Value Objects , the Entities and objects which assemblies these — the Aggregates. Aggregates can be connected only by identifiers. They cannot share any other data with each other.</p><p>The last layer is also thinner than in the previous model. Number of repositories corresponds to the number of aggregates in DDD so the application with the anemic model has more repositories than the one with the rich model.</p><h4>Easier changes and less bugs?</h4><p>Applying Domain Driven Design architecture gives developers some important benefits.</p><p>Thanks to dividing objects on the Entities and the Value Objects we can more precisely managing newly created objects in our application. Aggregates allow us to encapsulate parts of our domain so our API becomes simpler and changes inside aggregates are easier to implement (we don’t need to analyse our changes impact on some other parts of the domain because it doesn’t exist).</p><p>Less number of connections between domain elements reduce the risk of creating a bug while developing and modifying the code. Extended domain representation makes the code better reflecting how the domain experts describe the business rules. As a result, much easier is concluding about a correctness of solution, and if necessary, changing and developing it.</p><p>We encourage all of you to try DDD on daily basis. If you need some knowledge or support take a look at Eric Evans book <a href="https://www.goodreads.com/book/show/179133.Domain_Driven_Design">Domain-Driven Design: Tackling Complexity in the Heart of Software</a> or, maybe a little bit easier to understand, <a href="https://www.goodreads.com/book/show/15756865-implementing-domain-driven-design">Implementing Domain-Driven Design</a> written by Vaughn Vernon. We will try to give you a little bit of DDD concepts in next posts. Stay tuned.</p><p><a href="https://blog.pragmatists.com/refactoring-from-anemic-model-to-ddd-880d3dd3d45f">Refactoring from anemic model to DDD</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fcad346%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fcad346&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f2b0a73a41208cd75069a6bfc1b8777/href">https://medium.com/media/7f2b0a73a41208cd75069a6bfc1b8777/href</a></iframe><ul><li><a href="https://blog.pragmatists.com/visit-your-domain-objects-to-keep-em-legit-6b5d43e98ef0">Visit your domain objects to keep ’em legit!</a></li><li><a href="https://blog.pragmatists.com/retrying-consumer-architecture-in-the-apache-kafka-939ac4cb851a">Retrying consumer architecture in the Apache Kafka</a></li></ul><p>Find <a href="http://pragmatists.com/">Pragmatists</a> on <a href="https://www.facebook.com/pragmatistssf/">Facebook</a> and <a href="https://twitter.com/pragmatists/">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffdee9371a86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatists/domain-driven-design-vs-anemic-model-how-do-they-differ-ffdee9371a86">Domain-Driven Design vs. anemic model. How do they differ?</a> was originally published in <a href="https://medium.com/pragmatists">Pragmatists</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>