Enterprise Integration Zone is brought to you in partnership with:

Debasish specializes in leading delivery of enterprise scale solutions for various clients ranging from small ones to Fortune 500 companies. He is the technology evangelist of Anshin Software (http://www.anshinsoft.com) and takes pride in institutionalizing best practices in software design and programming. He loves to program in Java, Ruby, Erlang and Scala and has been trying desperately to get out of the unmanaged world of C++. Debasish is a DZone MVB and is not an employee of DZone and has posted 55 posts at DZone. You can read more from them at their website. View Full User Profile

Domain Services and Bounded Context using Akka - Part 2

03.31.2010
| 4775 views |
  • submit to reddit
In Part 1 of this series you saw how we can model a domain repository as an actor in Akka. It gives you declarative transaction semantics through Akka's STM and pluggable persistence engine support over a variety of data stores. As a result the domain model becomes cleaner. The repository that you design can take advantage of Akka's fault tolerance capabilities through supervisors that offer configurable lifecycle strategies.

One other important artifact of a domain model are the domain services. A domain service is not necessarily focused on any particular entity and is mostly centered around the verbs of the system. It models some actions or use cases involving multiple entities and is usually implemented as a stateless abstraction.

Using Akka you model a service as yet another actor. Domain services are coarse level abstractions and are the ones to receive requests from the clients. It can invoke other services or use any other entitites to do the job that it's supposed to do. No wonder a busy service gets requests from lots of consumers. Not only does it need to be stable, but it needs to ensure that all of it's other services with which it collaborates also stay alive while serving requests.

One of the services that it interacts with is the Domain Repository, which I discussed in the last post.

When you design a domain service using Akka actors, you can ensure that the service can make its collaborating services fault-tolerant through declarative or minimal programming effort. Akka runtime offers all the machinery to make implementation of fault tolerant services quite easy.

Consider the following domain service for management of Accounts, continuing our earlier example from the last post ..
trait AccountServer extends Actor {
// handle crash
faultHandler = Some(OneForOneStrategy(5, 5000))
trapExit = List(classOf[Exception])

// abstract val : the Repository Service
val storage: AccountRepository

// message handler
def receive = {
case Open(no, name) =>
storage ! New(Account(no, name, Calendar.getInstance.getTime, None, 100))
case msg @ Balance(_) => storage forward msg
case msg @ Post(_, _) => storage forward msg
case msg @ OpenM(as) => storage forward msg
}

// shutdown hook
override def shutdown = {
unlink(storage)
storage.stop
}
}
The message handler is a standard one that forwards client requests to the repository. Note tha use of the abstract val storage: AccountRepository that helps you defer committing to the concrete implementation class till instantiation of the service object.

AccountServer plays the role of a supervisor for the repository actor. The first 2 lines of code defines the strategy of supervision. OneForOneStrategy says that only the component that has crashed will be restarted. You can make it AllForOne also when the supervising actor will restart all of the actors that it's supervising if one of them crashes. trapExit defines the list of exceptions in the linked actor for which the supervising actor will take an action.

AccountServer is the aupervising actor for the repository. When it is shutdown it has to be unlinked fro the linked actors. This we do in the shutdown hook of the AccountServer.

But how do we link the Repository actor to our domain service actor ? Note that AccountServer is not a concrete object yet. We need to instantiate a concrete implementation of AccountRepository and assign it to storage in AccountServer. And link the two during this instantiation.

We define another trait that resolves the abstract val that we defined in AccountServer and provides a concrete instance of AccountRepository. spawnLink not only starts an instance of Redis based repository implementation, it also links the repository actor with the AccountServer ..
trait RedisAccountRepositoryFactory { this: Actor =>
val storage: AccountRepository = spawnLink(classOf[RedisAccountRepository])
}


Now we have all the components needed to instantiate a fault tolerant domain service object.

object AccountService extends
AccountServer with
RedisAccountRepositoryFactory {

// start the service
override def start: Actor = {
super.start
RemoteNode.start("localhost", 9999)
RemoteNode.register("account:service", this)
this
}
}
Have a look at the start method that starts the service on a remote node. We start a remote node and then register the current service under the id "account:service". Any client that needs to use the service can get hold of the service actor by specifying this id .. as in the following snippet ..
class AccountClient(val client: String) { 
import Actor.Sender.Self
val service = RemoteClient.actorFor("account:service", "localhost", 9999)

def open(no: String, name: String) = service ! Open(no, name)
def balance(no: String): Option[Int] =
(service !! Balance(no)).getOrElse(
throw new Exception("cannot get balance from server"))
def post(no: String, amount: Int) = service ! Post(no, amount)
def openMulti(as: List[(String, String)]) = service !!! OpenMulti(as)
}
Services defined using Akka can be made to run on remote nodes without much of an engineering hack. Akka runtime offers APIs for doing that. However, Akka never tries to hide from you the paradigms of distribution. You need to be aware of your distribution requirements and process and supervising hierarchies. Akka facilitates you to define them at the application level, doing the heavy lifting within its underlying implementation. This principle is inspired from Erlang's philosophy and is in sharp contrast to the RPC way of defining APIs. Along with the benefits of message based computation that decouples the sender and the receiver, Akka also enables you to handle states using its built-in STM and pluggable storage engine.

When you model a complex domain, you need to deal with multiple contexts, which Eric calls Bounded Contexts. Within a specific context you have a cohesive model with a set of domain behavior and abstractions. The interpretations of the same abstractions may change when you move to a different context within the same application. As a domain modeler you need to define your context boundaries very carefully using context maps and implement appropriate translation maps between multiple contexts.

Messaging is a great way to implement translation between contexts. You process messages within a context using domain services as above and at the end forward the same message or a translated one to the other contexts of the application. It can be in the form of push or you can also implement a publish/subscribe model between the related contexts. In the latter case, you use Akka-Camel integration that allows actors to send or receive messages through Camel end-points. In either case Akka provides you a world of options to implement loosely coupled domain contexts that form the components of your domain model.
References
Published at DZone with permission of Debasish Ghosh, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Peter Veentjer replied on Wed, 2010/03/31 - 8:49am

Hi Debasish,

normally, if developers care about it, concurrency control is done using a combination of:

- explicit optimistic locking

- explicit pessimistic locking (very database specific)

- setting the correct isolation level on the transaction.

But how is concurrency control regulated here using a NoSQL database? Akka provides abstractions on different storage mechanisms, but does it also provide abstractions on the isolation mechanism? I'm currently looking at some NoSQL storage solutions to see if they are a good fit as storage engine for Multiverse, but I'm still unclear about the concurrency control semantics provided by these engines. Not to mention providing an abstraction that works independant of the implementation.

 

Peter Veentjer

Multiverse: Software Transactional Memory for Java

http://multiverse.codehaus.org

Rehman Khan replied on Sat, 2012/02/25 - 4:37am

nice post.

How does this compare to DDDD? I'm not a DDDD (or DDD) expert, but I see some resemblances with DDDD because everything is done through events instead of direct modifications on the domain objects.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.