<?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 Fernando Martin on Medium]]></title>
        <description><![CDATA[Stories by Fernando Martin on Medium]]></description>
        <link>https://medium.com/@fernandoamartin?source=rss-9353d992922f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gZiL70uD0xARfq12CYfIjg.jpeg</url>
            <title>Stories by Fernando Martin on Medium</title>
            <link>https://medium.com/@fernandoamartin?source=rss-9353d992922f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:47:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fernandoamartin/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[Leave transaction control to the client]]></title>
            <link>https://fernandoamartin.medium.com/leave-transaction-control-to-the-client-ea6009348f37?source=rss-9353d992922f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6009348f37</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <dc:creator><![CDATA[Fernando Martin]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 20:53:12 GMT</pubDate>
            <atom:updated>2021-03-12T10:29:51.507Z</atom:updated>
            <content:encoded><![CDATA[<p>Every domain eventually runs into this. A business operation needs to maintain invariants between two or more entities on a given model. How can accomplish it without messing the model? Which component should be responsible for ensuring that?</p><p>For example, let’s say your domain has members and stories written by them and each profile should display the number of stories published by the member. The team decides to add a “storiesWrittenCount” to the Member Entity to avoid an extra query to the Story Collection.</p><p>A naive first attempt to satisfy that scenario would be:</p><pre>WriteStoryUseCase(story, member) {<br>  storyRepo.create(story)<br>  member.storiesWrittenCount++<br>  memberRepo.update(member)<br>}</pre><p>With this approach there is a risk of a failure on the members update after a successful story creation, breaking the story count invariant.</p><p>In the past, I have addressed the challenge of bringing transactional support between two or more entities in three different ways</p><h4>Option 1: Ignore it</h4><p>The risk is low and it’s late in the sprint. You don’t want to have another discussion in the retro about story pointing.</p><h4>Option 2: Leak the transactional implementation to the domain</h4><pre>WriteStoryUseCase(story, member) {<br>  MongoClient client = ...<br>  ClientSession clientSession = client.startSession()</pre><pre><em>  ...create story and update member...</em></pre><pre>  clientSession.withTransaction(...)<br>}</pre><p>At this point, your domain has a dependency on your infra layer (<em>Mongo</em> in this case) and is no longer “clean.”</p><h4>Option 3: Create a “StoryMemberRepo”</h4><pre>WriteStoryUseCase(story, member) {<br>  storyMemberRepo.writeStoryAndUpdateMember(story, member)<br>}</pre><p>Here we avoid the DB dependency, however, these repository mixes concepts and your codebase will likely end up with a <em>MemberRepo</em>, a <em>StoryRepo</em>, a <em>StoryMemberRepo</em>, a <em>StoryMemberNotificationRepo</em>, and so on. Now it’s no longer clear where to find functionality, leading to developer confusion and likely code duplication.</p><h3>An alternative</h3><p>While I was reading <a href="https://www.oreilly.com/library/view/domain-driven-design-tackling/0321125215/">Domain-Driven Design</a>, a particular sentence caught my attention and got me thinking: <strong><em>“Leave transaction control to the client.”</em></strong></p><p><strong><em>How about abstracting the concept of Transaction in the Domain and let the client initiate and commit units of works?</em></strong></p><h4>To the code!</h4><p>Kotlin and Mongo are the technologies of choice, you can check the full example in <a href="https://github.com/SenhorCastor/leave-transaction-control-to-the-client">Github</a>.</p><p>I defined the <em>Transaction:</em></p><pre>interface Transaction {<br>  fun start()<br>  fun commit()<br>}</pre><p>And its <em>Mongo</em> representation:</p><pre>class TransactionMongo private constructor(...) : Transaction {<br><strong>  </strong>private lateinit var session: ClientSession<br><br>  override fun start() {<br>    session = client.startSession()<br>    session.startTransaction()<br>  }<br><br>  override fun commit() {<br>    try {<br>      session.commitTransaction()<br>    } catch (e: Exception) {<br>      session.abortTransaction()<br>      throw TransactionAbortedException(e);<br>    } finally {<br>      session.close()<br>    }<br>  }<br>}</pre><p>Each functionality that saves an <em>Entity</em> in the <em>Repo</em> receives an optional <em>Transaction</em> as input and returns a <em>Transaction</em>:</p><pre>interface MemberRepo {<br>  fun save(member: Member, tr: Transaction? = null): Transaction<br>}</pre><p>With its implementation:</p><pre>class UserRepoMongo(private val mongoClient: MongoClient) : UserRepo {<br>  override fun save(user: User, tr: Transaction?): Transaction {</pre><pre>    val transactionUsed = mongoClient.getTransaction(tr)<br>    collection.save(transactionUsed.session(), user)</pre><pre>    return transactionUsed<br>  }<br>}</pre><p>I added an extension function to <em>MongoClient</em> for simplicity:</p><pre>fun MongoClient.getTransaction(tr: Transaction?): TransactionMongo {<br>  return if (transaction == null) {<br>    val newTransaction = TransactionMongo.create(this)<br>    newTransaction.start()<br>    return newTransaction<br>  } else {<br>    transaction as TransactionMongo<br>  }<br>}</pre><p>Finally, my use case looks like this:</p><pre>WriteStoryUseCase(story: Story, member: Member) {<br>  val tr = storyRepo.save(story);<br>  val memberUpdated = member.incrementStoriesWrittenCount()<br>  val trAfterSave =  memberRepo.save(memberUpdated, tr)<br>  trAfterSave.commit()<br>}</pre><p>With this approach, there is no dependency on the DB into the domain. Also, there are no mixing concepts of the two entities.</p><p>The complexity added is that now the model needs to deal with a new concept of <em>Transaction. </em>This shifts the responsibility of committing units of work to the model, which design-wise is a sound idea.</p><p>Finally, if the domain needs the creation of stories from many use cases, you can work on a service that does that and can be shared across your model.</p><h3>Model</h3><p>Let’s take a look at the model used to tackle this example (<a href="https://github.com/SenhorCastor/leave-transaction-control-to-the-client">Github</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGH78bK7_UOOYeF90wqrSQ.jpeg" /></figure><p>The App layer is the one that has global access to control the flow and perform the dependency injection.</p><p>The Repos and Transaction layers contain the details needed to implement the different entities and repositories defined in the inner layers. In this particular case, <em>Mongo</em>.</p><p>Use Cases is where the actual business logic resides, the<em> “domain layer.”</em></p><p>Here is the UML Diagram with the main components of the example:</p><p>You can see how the Use Case only has access to the entities and interface repos; the details are injected in the App layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njv-Ng5PVlmgLEctQh2N7g.jpeg" /></figure><p>And that’s all for now. Thank you for reading! This is my first ever medium story — hope you enjoyed it.</p><p>You can follow me on <a href="https://medium.com/@fernandoamartin">Medium</a>, <a href="https://twitter.com/Fer_A_Martin">Twitter</a>, and <a href="https://www.linkedin.com/in/fernandoamartin/">Linkedin</a>, where I will be sharing my thoughts and experiences in Software Development, Engineering Management, and more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6009348f37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>