SlideShare a Scribd company logo
1 of 16
Play + Scala + Reactive Mongo
Building a “reactive” data-access layer to
mongoDB
About Us
Max Kremer
Trialfire - co-founder
founded in June 2013
Autodesk - cloud solutions architect
Datastay - co-founder
Acquired by Autodesk 2011
Marconi Lanna
Trialfire - lead developer
founded in June 2013
Too many startups since
1996 to list here
Why “reactive”
Classic Synchronous Model:
With a traditional synchronous database driver, each
operation blocks the current thread until a response is
received.
More requests = more threads waiting = poor
scalability
What is “reactive”
Fully non-blocking and asynchronous
I/O operations
Play and async I/O
• Java NIO
• Non-blocking, asynchronous IO
• Process multiple HTTP requests with a single thread
• Large number of concurrent requests can be handled
with a few threads
Example
•A Play controller using a Future result:
package controllers
import play.api.mvc.{Action, Controller}
import concurrent.{ExecutionContext, Future}
import ExecutionContext.Implicits.global
object StuffController extends Controller {
def doStuff( ) = Action {
val someStuff = scala.concurrent.future {
models.Stuff.fetch( )
}
Async {
someStuff.map(value => Ok(value))
}
}
}
A word about Futures
•Represents a value that will be available later
•Execution contexts - think “thread pools”
•Futures are Monads
•Layer of abstraction over multi-threading
Data Access Layer
•Active Record Design Pattern
•Based on Futures
•Model = Case Class + Companion Object
•Stackable Traits
Persistence using Traits
import play.api.libs.json.Json
case class User
( id : Option[BSONObjectID]
, firstName: String
, lastName : String
, email : String
, password : String)
object User extends DataAccess[User] {
def collectionName = “user”
implicit val format = Json.format[User]
}
The Data Access Trait
trait DataAccess[M] {
def collectionName: String
implicit val format: Format[M]
private def db = ReactiveMongoPlugin.db
private def collection = db[JSONCollection](collectionName)
def insert(instance: M): (BSONObjectID, Future[LastError]) = {
val id = BSONObjectID.generate
(id, collection.insert(Json.toJson(instance) ++ id))
}
The Data Access Trait (cont’d)
def update(instance: M): Future[LastError] = {
instance.id map { id =>
collection.update(id, Json.toJson(instance))
} getOrElse Future.successful(LastError(err = Some("Invalid
ID"))
}
def byId(id: BSONObjectID): Future[Option[M]] = {
collection.find(id).cursor.headOption map {
_ flatMap { doc: JsObject =>
doc.asOpt[M]
}
}
}
Pros
•easy compared to sql
•no schemas
•no queries
•no migration
•it just works
conversion from/to json automatically
handled by play json api macros
Cons
•Futures all the way down…
•Futures all the way up, too...
•No joins
Cons (cont’d)
case class Book
( name : String
, author: Author)
case class author(name: String) {
lazy val books: Seq[Book] = Book.byAuthor(this)
}
lazy val books: Future[Seq[Book]] = Book.byAuthor(this)
val books = author.books
author.books map { books =>
...
}
Links
reactive mongo driver:
http://reactivemongo.org/
Play ReactiveMongo plugin:
https://github.com/ReactiveMongo/Play-eactiveMongo
The End
Thanks for listening
Future[Option[Applause]]
max@trialfire.com marconi@trialfire.com
We’re hiring!

More Related Content

What's hot

modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
Puppet
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 

What's hot (20)

Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And Groovy
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 
Leveraging Open Source for Database Development: Database Version Control wit...
Leveraging Open Source for Database Development: Database Version Control wit...Leveraging Open Source for Database Development: Database Version Control wit...
Leveraging Open Source for Database Development: Database Version Control wit...
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Scala play-framework
Scala play-frameworkScala play-framework
Scala play-framework
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
 
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
[1D1]신개념 N스크린 웹 앱 프레임워크 PARS
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Containerless in the Cloud with AWS Lambda
Containerless in the Cloud with AWS LambdaContainerless in the Cloud with AWS Lambda
Containerless in the Cloud with AWS Lambda
 

Similar to Play + scala + reactive mongo

J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
rsnarayanan
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
Kat Roque
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
titanlambda
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
IndicThreads
 

Similar to Play + scala + reactive mongo (20)

Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
From Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practiceFrom Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practice
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
CIRCUIT 2015 - Content API's For AEM Sites
CIRCUIT 2015 - Content API's For AEM SitesCIRCUIT 2015 - Content API's For AEM Sites
CIRCUIT 2015 - Content API's For AEM Sites
 
Integrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applicationsIntegrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applications
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Play + scala + reactive mongo

  • 1. Play + Scala + Reactive Mongo Building a “reactive” data-access layer to mongoDB
  • 2. About Us Max Kremer Trialfire - co-founder founded in June 2013 Autodesk - cloud solutions architect Datastay - co-founder Acquired by Autodesk 2011 Marconi Lanna Trialfire - lead developer founded in June 2013 Too many startups since 1996 to list here
  • 3. Why “reactive” Classic Synchronous Model: With a traditional synchronous database driver, each operation blocks the current thread until a response is received. More requests = more threads waiting = poor scalability
  • 4. What is “reactive” Fully non-blocking and asynchronous I/O operations
  • 5. Play and async I/O • Java NIO • Non-blocking, asynchronous IO • Process multiple HTTP requests with a single thread • Large number of concurrent requests can be handled with a few threads
  • 6. Example •A Play controller using a Future result: package controllers import play.api.mvc.{Action, Controller} import concurrent.{ExecutionContext, Future} import ExecutionContext.Implicits.global object StuffController extends Controller { def doStuff( ) = Action { val someStuff = scala.concurrent.future { models.Stuff.fetch( ) } Async { someStuff.map(value => Ok(value)) } } }
  • 7. A word about Futures •Represents a value that will be available later •Execution contexts - think “thread pools” •Futures are Monads •Layer of abstraction over multi-threading
  • 8. Data Access Layer •Active Record Design Pattern •Based on Futures •Model = Case Class + Companion Object •Stackable Traits
  • 9. Persistence using Traits import play.api.libs.json.Json case class User ( id : Option[BSONObjectID] , firstName: String , lastName : String , email : String , password : String) object User extends DataAccess[User] { def collectionName = “user” implicit val format = Json.format[User] }
  • 10. The Data Access Trait trait DataAccess[M] { def collectionName: String implicit val format: Format[M] private def db = ReactiveMongoPlugin.db private def collection = db[JSONCollection](collectionName) def insert(instance: M): (BSONObjectID, Future[LastError]) = { val id = BSONObjectID.generate (id, collection.insert(Json.toJson(instance) ++ id)) }
  • 11. The Data Access Trait (cont’d) def update(instance: M): Future[LastError] = { instance.id map { id => collection.update(id, Json.toJson(instance)) } getOrElse Future.successful(LastError(err = Some("Invalid ID")) } def byId(id: BSONObjectID): Future[Option[M]] = { collection.find(id).cursor.headOption map { _ flatMap { doc: JsObject => doc.asOpt[M] } } }
  • 12. Pros •easy compared to sql •no schemas •no queries •no migration •it just works conversion from/to json automatically handled by play json api macros
  • 13. Cons •Futures all the way down… •Futures all the way up, too... •No joins
  • 14. Cons (cont’d) case class Book ( name : String , author: Author) case class author(name: String) { lazy val books: Seq[Book] = Book.byAuthor(this) } lazy val books: Future[Seq[Book]] = Book.byAuthor(this) val books = author.books author.books map { books => ... }
  • 15. Links reactive mongo driver: http://reactivemongo.org/ Play ReactiveMongo plugin: https://github.com/ReactiveMongo/Play-eactiveMongo
  • 16. The End Thanks for listening Future[Option[Applause]] max@trialfire.com marconi@trialfire.com We’re hiring!