Leave transaction control to the client

Fernando Martin
Feb 10 · 4 min read

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?

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.

A naive first attempt to satisfy that scenario would be:

WriteStoryUseCase(story, member) {

With this approach there is a risk of a failure on the members update after a successful story creation, breaking the story count invariant.

In the past, I have addressed the challenge of bringing transactional support between two or more entities in three different ways

Option 1: Ignore it

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.

Option 2: Leak the transactional implementation to the domain

WriteStoryUseCase(story, member) {
MongoClient client = ...
ClientSession clientSession = client.startSession()

At this point, your domain has a dependency on your infra layer (Mongo in this case) and is no longer “clean.”

Option 3: Create a “StoryMemberRepo”

WriteStoryUseCase(story, member) {
storyMemberRepo.writeStoryAndUpdateMember(story, member)

Here we avoid the DB dependency, however, these repository mixes concepts and your codebase will likely end up with a MemberRepo, a StoryRepo, a StoryMemberRepo, a StoryMemberNotificationRepo, and so on. Now it’s no longer clear where to find functionality, leading to developer confusion and likely code duplication.

An alternative

While I was reading Domain-Driven Design, a particular sentence caught my attention and got me thinking: “Leave transaction control to the client.”

How about abstracting the concept of Transaction in the Domain and let the client initiate and commit units of works?

To the code!

Kotlin and Mongo are the technologies of choice, you can check the full example in Github.

I defined the Transaction:

interface Transaction {
fun start()
fun commit()

And its Mongo representation:

class TransactionMongo private constructor(...) : Transaction {
private lateinit var session: ClientSession

override fun start() {
session = client.startSession()

override fun commit() {
try {
} catch (e: Exception) {
throw TransactionAbortedException(e);
} finally {

Each functionality that saves an Entity in the Repo receives an optional Transaction as input and returns a Transaction:

interface MemberRepo {
fun save(member: Member, tr: Transaction? = null): Transaction

With its implementation:

class UserRepoMongo(private val mongoClient: MongoClient) : UserRepo {
override fun save(user: User, tr: Transaction?): Transaction {

I added an extension function to MongoClient for simplicity:

fun MongoClient.getTransaction(tr: Transaction?): TransactionMongo {
return if (transaction == null) {
val newTransaction = TransactionMongo.create(this)
return newTransaction
} else {
transaction as TransactionMongo

Finally, my use case looks like this:

WriteStoryUseCase(story: Story, member: Member) {
val tr = storyRepo.save(story);
val memberUpdated = member.incrementStoriesWrittenCount()
val trAfterSave = memberRepo.save(memberUpdated, tr)

With this approach, there is no dependency on the DB into the domain. Also, there are no mixing concepts of the two entities.

The complexity added is that now the model needs to deal with a new concept of Transaction. This shifts the responsibility of committing units of work to the model, which design-wise is a sound idea.

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.


Let’s take a look at the model used to tackle this example (Github).

The App layer is the one that has global access to control the flow and perform the dependency injection.

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, Mongo.

Use Cases is where the actual business logic resides, the “domain layer.”

Here is the UML Diagram with the main components of the example:

You can see how the Use Case only has access to the entities and interface repos; the details are injected in the App layer.

And that’s all for now. Thank you for reading! This is my first ever medium story — hope you enjoyed it.

You can follow me on Medium, Twitter, and Linkedin, where I will be sharing my thoughts and experiences in Software Development, Engineering Management, and more.

Nerd For Tech

From Confusion to Clarification

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store