SlideShare a Scribd company logo
1 of 41
Download to read offline
Lightbend Lagom
Microservices “Just Right”
Mirco Dotta
@mircodotta
Scala Days Berlin - June 16, 2016
Lagom - [lah-gome]
Adequate, sufficient, just right
Agenda
● Why Lagom?
● Lagom dive in
○ Development Environment
○ Service API
○ Persistence API
● Running in Production
Why Lagom?
● Opinionated
● Developer experience matters!
○ No brittle script to run your services
○ Inter-service communication just works
○ Services are automatically reloaded on code change
● Takes you through to production deployment
● sbt build tool (developer environment)
● Play 2.5
● Akka 2.4 (clustering, streams, persistence)
● Cassandra (default data store)
● Jackson (JSON serialization)
● Guice (DI)
Under the hood
Enough slides,
Demo time
your-lagom-system → Project root
└ helloworld-api → helloworld api project
└ helloworld-impl → helloworld implementation
project
└ project → sbt configuration files
└ plugins.sbt → sbt plugins
└ build.sbt → Your project build file
Anatomy of a Lagom project
Each service definition is split into two sbt projects: api & impl
Service API
Service definition
// this source is placed in your api project
trait HelloService extends Service {
override def descriptor(): Descriptor = {
named("helloservice").withCalls(
namedCall("/hello", sayHello _)
)
}
def sayHello(): ServiceCall[String, String]
}
ServiceCall explained
● ServiceCall can be invoked when consuming a service:
○ Request: type of incoming request message (e.g. String)
○ Response: type of outgoing response message (e.g. String)
● JSON is the default serialization format for request/response messages
● There are two kinds of request/response messages:
○ Strict
○ Streamed
trait ServiceCall[Request, Response] {
def invoke(request: Request): Future[Response]
}
Strict Messages
Strict messages are fully buffered into memory
override def descriptor(): Descriptor = {
named("helloservice").withCalls(
namedCall("/hello", sayHello _)
)
}
def sayHello(): ServiceCall[String, String]
Streamed Messages
override def descriptor(): Descriptor = {
named("clock").withCalls(
pathCall("/tick/:interval", tick _)
)
}
def tick(interval: Int): ServiceCall[String, Source[String, _]]
● A streamed message is of type Source (an Akka streams API)
● Back-pressured, asynchronous handling of messages
● Lagom will select transport protocol (currently WebSockets)
Remember the Service definition?
// this source is placed in your api project
trait HelloService extends Service {
override def descriptor(): Descriptor = {
named("helloservice").withCalls(
namedCall(sayHello _)
)
}
def sayHello(): ServiceCall[String, String]
}
Here is the Service implementation
// this source is placed in your implementation project
class HelloServiceImpl extends HelloService {
override def sayHello(): ServiceCall[String, String] = {
name => Future.successful(s"Hello, $name!")
}
}
Inter-service communication
class MyServiceImpl @Inject()(helloService: HelloService)
(implicit ec: ExecutionContext) extends MyService {
override def sayHelloLagom(): ServiceCall[NotUsed, String] = unused => {
val response = helloService.sayHello().invoke("Lagom")
response.map(answer => s"Hello service said: $answer")
}
}
Inter-service communication
Do you see a problem?
class MyServiceImpl @Inject()(helloService: HelloService)
(implicit ec: ExecutionContext) extends MyService {
override def sayHelloLagom(): ServiceCall[NotUsed, String] = unused => {
val response = helloService.sayHello().invoke("Lagom")
response.map(answer => s"Hello service said: $answer")
}
}
Persistence API
Principles
● Each service owns its data
○ Only the service has direct access to the DB
● We advocate the use of Event Sourcing (ES) and CQRS
○ ES: Capture all state’s changes as events
○ CQRS: separate models for write and read
Benefits of Event Sourcing/CQRS
● Allows you to time travel
● Audit log
● Future business opportunities
● No need for ORM
● No database migration script, ever!
● Performance & Scalability
● Testability & Debuggability
Event Sourcing: Write Side
● Create your own Command and Event classes
● Subclass PersistentEntity
○ Define Command and Event handlers
○ Can be accessed from anywhere in the cluster
○ (corresponds to an Aggregate Root in DDD)
Let’s implement the add a friend functionality in chirper
Event Sourcing: Example
Demo
Event Sourcing: Example
1. Create a AddFriend command class
2. Create a FriendAdded event class
3. Define a FriendEntity holding the state (i.e., who are the
friends of a specific user)
a. Create a command handler for the AddFriend command
b. Create an event handler for the FriendAdded event
Event Sourcing: Example cont’d
1. Create a AddFriend command class
2. Create a FriendAdded event class
3. Define a FriendEntity holding the state of what are friends of
a given user
4. Create a command handler for the AddFriend command
5. Create an event handler for the FriendAdded event
Event Sourcing: Example cont’d
Create the Command classes
sealed trait FriendCommand extends Jsonable
case class AddFriend(friendId: String) extends
PersistentEntity.ReplyType[Done] with FriendCommand
// more friend commands
Event Sourcing: Example cont’d
1. Create a AddFriend command class
2. Create a FriendAdded event class
3. Define a FriendEntity holding the state of what are friends of
a given user
4. Create a command handler for the AddFriend command
5. Create an event handler for the FriendAdded event
Event Sourcing: Example cont’d
Create the Event classes
sealed trait FriendEvent extends Jsonable
case class FriendAdded(userId: String, friendId: String,
timestamp: Instant = Instant.now()) extends FriendEvent
// more friend events
Event Sourcing: Example cont’d
1. Create a AddFriend command class
2. Create a FriendAdded event class
3. Define a FriendEntity holding the state of what are friends of
a given user
4. Create a command handler for the AddFriend command
5. Create an event handler for the FriendAdded event
Event Sourcing: Example cont’d
class FriendEntity extends
PersistentEntity[FriendCommand, FriendEvent, FriendState] {
def initialBehavior(snapshotState: Optional[FriendState]): Behavior =
// TODO: define command and event handlers
}
Create a subclass of PersistentEntity
Event Sourcing: Example cont’d
Create the State class
case class FriendState(user: Option[User]) extends Jsonable {
def addFriend(friendUserId: String): FriendState = user match {
case None => throw new IllegalStateException(
"friend can't be added before user is created")
case Some(user) =>
val newFriends = user.friends :+ friendUserId
FriendState(Some(user.copy(friends = newFriends)))
}
}
Event Sourcing: Example cont’d
1. Create a AddFriend command class
2. Create a FriendAdded event class
3. Define a FriendEntity holding the state of what are friends of
a given user
4. Create a command handler for the AddFriend command
5. Create an event handler for the FriendAdded event
Event Sourcing: Example cont’d
val b: Behavior = newBehaviorBuilder(/*...*/)
b.setCommandHandler(classOf[AddFriend],
(cmd: AddFriend, ctx: CommandContext[Done]) => state.user match {
case None =>
ctx.invalidCommand(s"User ${entityId} is not created")
ctx.done()
case Some(user) =>
ctx.thenPersist(FriendAdded(user.userId, cmd.friendUserId),
(evt: FriendAdded) => ctx.reply(Done))
})
Event Sourcing: Example cont’d
1. Create a AddFriend command class
2. Create a FriendAdded event class
3. Define a FriendEntity holding the state of what are friends of
a given user
4. Create a command handler for the AddFriend command
5. Create an event handler for the FriendAdded event
b.setEventHandler(classOf[FriendAdded],
(evt: FriendAdded) => state.addFriend(evt.friendId))
Event Sourcing: Example cont’d
No side-effects in the event handler!
class FriendService extends Service {
override def descriptor(): Descriptor = {
named("friendservice").withCalls(
pathCall("/api/users/:userId/friends", addFriend _),
...
)
}
def addFriend(userId: String): ServiceCall[FriendId, NotUsed]
}
Event Sourcing: Example cont’d
And we can now finally implement the service call
class FriendServiceImpl @Inject() (persistentEntities: PersistentEntityRegistry)
(implicit ec: ExecutionContext) extends FriendService {
// at service startup we must register the needed entities
persistentEntities.register(classOf[FriendEntity])
def addFriend(userId: String): ServiceCall[FriendId, NotUsed] = request => {
val ref = persistentEntities.refFor(classOf[FriendEntity], userId)
ref.ask[Done, AddFriend](AddFriend(request.friendId))
}
// ...
}
Event Sourcing: Example cont’d
Event Sourcing: Read Side
● Tightly integrated with Cassandra
● Create the query tables:
○ Subclass CassandraReadSideProcessor
○ Consumes events produced by the PersistentEntity and
updates tables in Cassandra optimized for queries
● Retrieving data: Cassandra Query Language
○ e.g., SELECT id, title FROM postsummary
Running in Production
● sbt-native packager is used to produce zip, MSI, RPM, Docker
● Lightbend ConductR* (our container orchestration tool)
● Lightbend Reactive Platform*
○ Split Brain Resolver (for Akka cluster)
○ Lightbend Monitoring
*Requires a Lightbend subscription (but it is free to use during development)
Current[Lagom]
● Current version is 1.0.0-RC1
● Java API, but no Scala API yet
○ We are working on the Scala API
○ But using Scala with the Java API works quite well! https:
//github.com/dotta/activator-lagom-scala-chirper
Future[Lagom]
● Maven support
● Message broker integration
● Scala API
● Support for other cluster orchestration tools
○ Want Kubernetes support? Contribute! https://github.
com/huntc/kubernetes-lib
● Support for writing integration tests
● Swagger integration
Next: Seq[Step]
● Try Lagom yourself
○ https://lightbend.com/lagom
● Using Scala with Lagom
○ https://github.com/dotta/activator-lagom-scala-
chirper/releases/tag/v02_scaladays_berlin_2016
● Lagom on Github
○ https://github.com/lagom/lagom
● Read Jonas Bonér's free ebook Reactive Services Architecture
○ https://lightbend.com/reactive-microservices-architecture
● Great presentation by Greg Young on why you should use ES
○ https://www.youtube.com/watch?v=JHGkaShoyNs
Thank you for listening!
@mircodotta
@lagom

More Related Content

What's hot

Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentationGene Chang
 
Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Knoldus Inc.
 
JVM languages "flame wars"
JVM languages "flame wars"JVM languages "flame wars"
JVM languages "flame wars"Gal Marder
 
Spark real world use cases and optimizations
Spark real world use cases and optimizationsSpark real world use cases and optimizations
Spark real world use cases and optimizationsGal Marder
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Dive into spark2
Dive into spark2Dive into spark2
Dive into spark2Gal Marder
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a clusterGal Marder
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala MacrosKnoldus Inc.
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Monica Beckwith
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scaladatamantra
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Neo4 + Grails
Neo4 + GrailsNeo4 + Grails
Neo4 + Grailsstasimus
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterpriseRafael Bagmanov
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarGal Marder
 
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Gal Marder
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overviewstasimus
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoTaro L. Saito
 

What's hot (20)

Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2Introduction to Apache Kafka- Part 2
Introduction to Apache Kafka- Part 2
 
JVM languages "flame wars"
JVM languages "flame wars"JVM languages "flame wars"
JVM languages "flame wars"
 
Spark real world use cases and optimizations
Spark real world use cases and optimizationsSpark real world use cases and optimizations
Spark real world use cases and optimizations
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Dive into spark2
Dive into spark2Dive into spark2
Dive into spark2
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Neo4 + Grails
Neo4 + GrailsNeo4 + Grails
Neo4 + Grails
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
 

Viewers also liked

Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)mircodotta
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...mircodotta
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Futuremircodotta
 
Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...
Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...
Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...Lightbend
 
Social Media & Networking - The Evolving Workforce
Social Media & Networking - The Evolving WorkforceSocial Media & Networking - The Evolving Workforce
Social Media & Networking - The Evolving WorkforceTodd Wheatland
 
Local Government Balances Security, Flexibility and Productivity with BlackBe...
Local Government Balances Security, Flexibility and Productivity with BlackBe...Local Government Balances Security, Flexibility and Productivity with BlackBe...
Local Government Balances Security, Flexibility and Productivity with BlackBe...BlackBerry
 
หน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ต
หน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ตหน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ต
หน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ตTa Khanittha
 
ADN Antreprenor 2016 - Felix Tataru, GMP
ADN Antreprenor 2016 - Felix Tataru, GMPADN Antreprenor 2016 - Felix Tataru, GMP
ADN Antreprenor 2016 - Felix Tataru, GMPGabriel Barliga
 
Seguridad de la Informacion
Seguridad de la InformacionSeguridad de la Informacion
Seguridad de la InformacionNFAG DTLF
 
6 Healthy Mother's Day Gifts
6 Healthy Mother's Day Gifts6 Healthy Mother's Day Gifts
6 Healthy Mother's Day GiftsEason Chan
 
Towards a Grand Unified Theory of Systems Engineering (GUTSE)
Towards a Grand Unified Theory of Systems Engineering (GUTSE)Towards a Grand Unified Theory of Systems Engineering (GUTSE)
Towards a Grand Unified Theory of Systems Engineering (GUTSE)Joseph KAsser
 
Fitriana bakar tugas 1 so ii
Fitriana bakar tugas 1 so iiFitriana bakar tugas 1 so ii
Fitriana bakar tugas 1 so iifhitCharis
 
Mobile application development |#Mobileapplicationdevelopment
Mobile application development |#MobileapplicationdevelopmentMobile application development |#Mobileapplicationdevelopment
Mobile application development |#MobileapplicationdevelopmentMobile App Developers India
 
M2 t1 planificador_aamtic version final numeral 5
M2 t1 planificador_aamtic  version final numeral 5M2 t1 planificador_aamtic  version final numeral 5
M2 t1 planificador_aamtic version final numeral 5Polo Apolo
 
Normas apa Raisa Mendoza
Normas apa Raisa MendozaNormas apa Raisa Mendoza
Normas apa Raisa MendozaYadira Fuentes
 
شهادة الماجستر
شهادة الماجسترشهادة الماجستر
شهادة الماجسترSaleem Abudayeh
 

Viewers also liked (20)

Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...
Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...
Enterprise Development Trends 2016 - Cloud, Container and Microservices Insig...
 
Frraactioon
FrraactioonFrraactioon
Frraactioon
 
Social Media & Networking - The Evolving Workforce
Social Media & Networking - The Evolving WorkforceSocial Media & Networking - The Evolving Workforce
Social Media & Networking - The Evolving Workforce
 
Perunapuu esittely 4
Perunapuu esittely 4Perunapuu esittely 4
Perunapuu esittely 4
 
Local Government Balances Security, Flexibility and Productivity with BlackBe...
Local Government Balances Security, Flexibility and Productivity with BlackBe...Local Government Balances Security, Flexibility and Productivity with BlackBe...
Local Government Balances Security, Flexibility and Productivity with BlackBe...
 
หน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ต
หน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ตหน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ต
หน่วยที่ 9 ระบบเครือข่ายอินเทอร์เน็ต
 
Mas loco que una cabra
Mas loco que una cabraMas loco que una cabra
Mas loco que una cabra
 
Things I Carry
Things I CarryThings I Carry
Things I Carry
 
ADN Antreprenor 2016 - Felix Tataru, GMP
ADN Antreprenor 2016 - Felix Tataru, GMPADN Antreprenor 2016 - Felix Tataru, GMP
ADN Antreprenor 2016 - Felix Tataru, GMP
 
Seguridad de la Informacion
Seguridad de la InformacionSeguridad de la Informacion
Seguridad de la Informacion
 
6 Healthy Mother's Day Gifts
6 Healthy Mother's Day Gifts6 Healthy Mother's Day Gifts
6 Healthy Mother's Day Gifts
 
Towards a Grand Unified Theory of Systems Engineering (GUTSE)
Towards a Grand Unified Theory of Systems Engineering (GUTSE)Towards a Grand Unified Theory of Systems Engineering (GUTSE)
Towards a Grand Unified Theory of Systems Engineering (GUTSE)
 
Fitriana bakar tugas 1 so ii
Fitriana bakar tugas 1 so iiFitriana bakar tugas 1 so ii
Fitriana bakar tugas 1 so ii
 
Mobile application development |#Mobileapplicationdevelopment
Mobile application development |#MobileapplicationdevelopmentMobile application development |#Mobileapplicationdevelopment
Mobile application development |#Mobileapplicationdevelopment
 
M2 t1 planificador_aamtic version final numeral 5
M2 t1 planificador_aamtic  version final numeral 5M2 t1 planificador_aamtic  version final numeral 5
M2 t1 planificador_aamtic version final numeral 5
 
Normas apa Raisa Mendoza
Normas apa Raisa MendozaNormas apa Raisa Mendoza
Normas apa Raisa Mendoza
 
شهادة الماجستر
شهادة الماجسترشهادة الماجستر
شهادة الماجستر
 

Similar to Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)

Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive AppsJorge Ortiz
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsPSTechSerbia
 
Building a custom Oracle ADF Component
Building a custom Oracle ADF ComponentBuilding a custom Oracle ADF Component
Building a custom Oracle ADF ComponentWilfred van der Deijl
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterHaehnchen
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Eventstkramar
 
Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Docker, Inc.
 
Let CodeCommit work for you
Let CodeCommit work for youLet CodeCommit work for you
Let CodeCommit work for youJorisConijn
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixManish Pandit
 
Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)Vitaly Brusentsev
 
Fabric - Realtime stream processing framework
Fabric - Realtime stream processing frameworkFabric - Realtime stream processing framework
Fabric - Realtime stream processing frameworkShashank Gautam
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Paco de la Cruz
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1Paras Mendiratta
 
How We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADFHow We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADFSeanGraham5
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwrdeimos
 

Similar to Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin) (20)

Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Adf component tech14
Adf component tech14Adf component tech14
Adf component tech14
 
Building a custom Oracle ADF Component
Building a custom Oracle ADF ComponentBuilding a custom Oracle ADF Component
Building a custom Oracle ADF Component
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Events
 
Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...
 
Let CodeCommit work for you
Let CodeCommit work for youLet CodeCommit work for you
Let CodeCommit work for you
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
 
Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)Event sourcing in the functional world (22 07-2021)
Event sourcing in the functional world (22 07-2021)
 
Fabric - Realtime stream processing framework
Fabric - Realtime stream processing frameworkFabric - Realtime stream processing framework
Fabric - Realtime stream processing framework
 
Going Serverless
Going ServerlessGoing Serverless
Going Serverless
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
How We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADFHow We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADF
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 

More from mircodotta

Akka streams scala italy2015
Akka streams scala italy2015Akka streams scala italy2015
Akka streams scala italy2015mircodotta
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)mircodotta
 
Scala: Simplifying Development
Scala: Simplifying DevelopmentScala: Simplifying Development
Scala: Simplifying Developmentmircodotta
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)mircodotta
 

More from mircodotta (6)

Akka streams scala italy2015
Akka streams scala italy2015Akka streams scala italy2015
Akka streams scala italy2015
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 
Scala: Simplifying Development
Scala: Simplifying DevelopmentScala: Simplifying Development
Scala: Simplifying Development
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
 

Recently uploaded

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 

Recently uploaded (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)

  • 1. Lightbend Lagom Microservices “Just Right” Mirco Dotta @mircodotta Scala Days Berlin - June 16, 2016
  • 2. Lagom - [lah-gome] Adequate, sufficient, just right
  • 3. Agenda ● Why Lagom? ● Lagom dive in ○ Development Environment ○ Service API ○ Persistence API ● Running in Production
  • 4. Why Lagom? ● Opinionated ● Developer experience matters! ○ No brittle script to run your services ○ Inter-service communication just works ○ Services are automatically reloaded on code change ● Takes you through to production deployment
  • 5. ● sbt build tool (developer environment) ● Play 2.5 ● Akka 2.4 (clustering, streams, persistence) ● Cassandra (default data store) ● Jackson (JSON serialization) ● Guice (DI) Under the hood
  • 7. your-lagom-system → Project root └ helloworld-api → helloworld api project └ helloworld-impl → helloworld implementation project └ project → sbt configuration files └ plugins.sbt → sbt plugins └ build.sbt → Your project build file Anatomy of a Lagom project Each service definition is split into two sbt projects: api & impl
  • 9. Service definition // this source is placed in your api project trait HelloService extends Service { override def descriptor(): Descriptor = { named("helloservice").withCalls( namedCall("/hello", sayHello _) ) } def sayHello(): ServiceCall[String, String] }
  • 10. ServiceCall explained ● ServiceCall can be invoked when consuming a service: ○ Request: type of incoming request message (e.g. String) ○ Response: type of outgoing response message (e.g. String) ● JSON is the default serialization format for request/response messages ● There are two kinds of request/response messages: ○ Strict ○ Streamed trait ServiceCall[Request, Response] { def invoke(request: Request): Future[Response] }
  • 11. Strict Messages Strict messages are fully buffered into memory override def descriptor(): Descriptor = { named("helloservice").withCalls( namedCall("/hello", sayHello _) ) } def sayHello(): ServiceCall[String, String]
  • 12. Streamed Messages override def descriptor(): Descriptor = { named("clock").withCalls( pathCall("/tick/:interval", tick _) ) } def tick(interval: Int): ServiceCall[String, Source[String, _]] ● A streamed message is of type Source (an Akka streams API) ● Back-pressured, asynchronous handling of messages ● Lagom will select transport protocol (currently WebSockets)
  • 13. Remember the Service definition? // this source is placed in your api project trait HelloService extends Service { override def descriptor(): Descriptor = { named("helloservice").withCalls( namedCall(sayHello _) ) } def sayHello(): ServiceCall[String, String] }
  • 14. Here is the Service implementation // this source is placed in your implementation project class HelloServiceImpl extends HelloService { override def sayHello(): ServiceCall[String, String] = { name => Future.successful(s"Hello, $name!") } }
  • 15. Inter-service communication class MyServiceImpl @Inject()(helloService: HelloService) (implicit ec: ExecutionContext) extends MyService { override def sayHelloLagom(): ServiceCall[NotUsed, String] = unused => { val response = helloService.sayHello().invoke("Lagom") response.map(answer => s"Hello service said: $answer") } }
  • 16. Inter-service communication Do you see a problem? class MyServiceImpl @Inject()(helloService: HelloService) (implicit ec: ExecutionContext) extends MyService { override def sayHelloLagom(): ServiceCall[NotUsed, String] = unused => { val response = helloService.sayHello().invoke("Lagom") response.map(answer => s"Hello service said: $answer") } }
  • 18. Principles ● Each service owns its data ○ Only the service has direct access to the DB ● We advocate the use of Event Sourcing (ES) and CQRS ○ ES: Capture all state’s changes as events ○ CQRS: separate models for write and read
  • 19. Benefits of Event Sourcing/CQRS ● Allows you to time travel ● Audit log ● Future business opportunities ● No need for ORM ● No database migration script, ever! ● Performance & Scalability ● Testability & Debuggability
  • 20. Event Sourcing: Write Side ● Create your own Command and Event classes ● Subclass PersistentEntity ○ Define Command and Event handlers ○ Can be accessed from anywhere in the cluster ○ (corresponds to an Aggregate Root in DDD)
  • 21. Let’s implement the add a friend functionality in chirper Event Sourcing: Example Demo
  • 22. Event Sourcing: Example 1. Create a AddFriend command class 2. Create a FriendAdded event class 3. Define a FriendEntity holding the state (i.e., who are the friends of a specific user) a. Create a command handler for the AddFriend command b. Create an event handler for the FriendAdded event
  • 23. Event Sourcing: Example cont’d 1. Create a AddFriend command class 2. Create a FriendAdded event class 3. Define a FriendEntity holding the state of what are friends of a given user 4. Create a command handler for the AddFriend command 5. Create an event handler for the FriendAdded event
  • 24. Event Sourcing: Example cont’d Create the Command classes sealed trait FriendCommand extends Jsonable case class AddFriend(friendId: String) extends PersistentEntity.ReplyType[Done] with FriendCommand // more friend commands
  • 25. Event Sourcing: Example cont’d 1. Create a AddFriend command class 2. Create a FriendAdded event class 3. Define a FriendEntity holding the state of what are friends of a given user 4. Create a command handler for the AddFriend command 5. Create an event handler for the FriendAdded event
  • 26. Event Sourcing: Example cont’d Create the Event classes sealed trait FriendEvent extends Jsonable case class FriendAdded(userId: String, friendId: String, timestamp: Instant = Instant.now()) extends FriendEvent // more friend events
  • 27. Event Sourcing: Example cont’d 1. Create a AddFriend command class 2. Create a FriendAdded event class 3. Define a FriendEntity holding the state of what are friends of a given user 4. Create a command handler for the AddFriend command 5. Create an event handler for the FriendAdded event
  • 28. Event Sourcing: Example cont’d class FriendEntity extends PersistentEntity[FriendCommand, FriendEvent, FriendState] { def initialBehavior(snapshotState: Optional[FriendState]): Behavior = // TODO: define command and event handlers } Create a subclass of PersistentEntity
  • 29. Event Sourcing: Example cont’d Create the State class case class FriendState(user: Option[User]) extends Jsonable { def addFriend(friendUserId: String): FriendState = user match { case None => throw new IllegalStateException( "friend can't be added before user is created") case Some(user) => val newFriends = user.friends :+ friendUserId FriendState(Some(user.copy(friends = newFriends))) } }
  • 30. Event Sourcing: Example cont’d 1. Create a AddFriend command class 2. Create a FriendAdded event class 3. Define a FriendEntity holding the state of what are friends of a given user 4. Create a command handler for the AddFriend command 5. Create an event handler for the FriendAdded event
  • 31. Event Sourcing: Example cont’d val b: Behavior = newBehaviorBuilder(/*...*/) b.setCommandHandler(classOf[AddFriend], (cmd: AddFriend, ctx: CommandContext[Done]) => state.user match { case None => ctx.invalidCommand(s"User ${entityId} is not created") ctx.done() case Some(user) => ctx.thenPersist(FriendAdded(user.userId, cmd.friendUserId), (evt: FriendAdded) => ctx.reply(Done)) })
  • 32. Event Sourcing: Example cont’d 1. Create a AddFriend command class 2. Create a FriendAdded event class 3. Define a FriendEntity holding the state of what are friends of a given user 4. Create a command handler for the AddFriend command 5. Create an event handler for the FriendAdded event
  • 33. b.setEventHandler(classOf[FriendAdded], (evt: FriendAdded) => state.addFriend(evt.friendId)) Event Sourcing: Example cont’d No side-effects in the event handler!
  • 34. class FriendService extends Service { override def descriptor(): Descriptor = { named("friendservice").withCalls( pathCall("/api/users/:userId/friends", addFriend _), ... ) } def addFriend(userId: String): ServiceCall[FriendId, NotUsed] } Event Sourcing: Example cont’d And we can now finally implement the service call
  • 35. class FriendServiceImpl @Inject() (persistentEntities: PersistentEntityRegistry) (implicit ec: ExecutionContext) extends FriendService { // at service startup we must register the needed entities persistentEntities.register(classOf[FriendEntity]) def addFriend(userId: String): ServiceCall[FriendId, NotUsed] = request => { val ref = persistentEntities.refFor(classOf[FriendEntity], userId) ref.ask[Done, AddFriend](AddFriend(request.friendId)) } // ... } Event Sourcing: Example cont’d
  • 36. Event Sourcing: Read Side ● Tightly integrated with Cassandra ● Create the query tables: ○ Subclass CassandraReadSideProcessor ○ Consumes events produced by the PersistentEntity and updates tables in Cassandra optimized for queries ● Retrieving data: Cassandra Query Language ○ e.g., SELECT id, title FROM postsummary
  • 37. Running in Production ● sbt-native packager is used to produce zip, MSI, RPM, Docker ● Lightbend ConductR* (our container orchestration tool) ● Lightbend Reactive Platform* ○ Split Brain Resolver (for Akka cluster) ○ Lightbend Monitoring *Requires a Lightbend subscription (but it is free to use during development)
  • 38. Current[Lagom] ● Current version is 1.0.0-RC1 ● Java API, but no Scala API yet ○ We are working on the Scala API ○ But using Scala with the Java API works quite well! https: //github.com/dotta/activator-lagom-scala-chirper
  • 39. Future[Lagom] ● Maven support ● Message broker integration ● Scala API ● Support for other cluster orchestration tools ○ Want Kubernetes support? Contribute! https://github. com/huntc/kubernetes-lib ● Support for writing integration tests ● Swagger integration
  • 40. Next: Seq[Step] ● Try Lagom yourself ○ https://lightbend.com/lagom ● Using Scala with Lagom ○ https://github.com/dotta/activator-lagom-scala- chirper/releases/tag/v02_scaladays_berlin_2016 ● Lagom on Github ○ https://github.com/lagom/lagom ● Read Jonas Bonér's free ebook Reactive Services Architecture ○ https://lightbend.com/reactive-microservices-architecture ● Great presentation by Greg Young on why you should use ES ○ https://www.youtube.com/watch?v=JHGkaShoyNs
  • 41. Thank you for listening! @mircodotta @lagom