SlideShare a Scribd company logo
Concurrency at the 
Database Layer 
Scala / Reactive Mongo Example 
For Reactive Programming Enthusiasts Denver 
Mark Wilson
Why ? 
The Contextual Explanation 
• To be non-blocking all the way through 
• Because of Amdahl’s law 
• and the Reactive Manifesto
Amdahl’s Law 
“…Therefore it is important that the entire solution is 
asynchronous and non-blocking.” 
- Reactive Manifesto
Reactive 
• Use resources better to achieve scale, resilience, 
and performance. 
• Do this by replacing thread managed state with 
event-driven messaging 
• Replace synchronous implementations with non-blocking 
code. 
• Pillars: Responsive, Scalable, Event-Driven, 
Resilient
Why (cont.) ? 
The Specific Explanations for concurrency at the database layer. 
• Because most db drivers are blocking. 
• Because concurrency beats thread tuning at 
large scale. 
• Because it is faster on multicore machines (which 
most are) and more fully utilizes the machine 
recourses
Presentation 
Focus and Outline 
What I wanted to achieve 
• Restful services with GET, POST, PUT supported by a 
concurrent database layer 
• Demo app resembling a real-world structure 
• Coding with the library. Example implementation 
• Some load testing blocking vs non-blocking.
Demo Application 
“Whale Sighting” Single Page application 
https://github.com/p44/FishStore 
• The UI 
! 
• The Services 
! 
• The DB Layer
The POST 
POST {"breed":"Sei Whale","count":1,"description":"Pretty whale."}
Concurrency with Future(s). 
So What’s a Future? 
• A future is an object holding a value that may become 
available at some point in time. 
• A future is either completed or not completed 
• A completed future is either: 
• Successful(value) 
• Failed(exception) 
• A future frees the current thread by establishing a callback
Future Example 
import scala.concurrent.ExecutionContext.Implicits.global 
import scala.concurrent.Future 
import scala.util.{Failure, Success} 
! 
val fs: Future[String] = Future { “a” + “b” } 
fs.onComplete { 
case Success(x) => println(x) 
case Failure(e) => throw e 
} 
Execution contexts execute tasks submitted to them, 
and you can think of execution contexts as thread pools.
The Insert 
val fResult: Future[LastError] = WhaleSighting.insertOneAsFuture(db, ws) 
object WhaleSighting extends Persistable[WhaleSighting] { 
… 
} 
! 
trait Persistable[T] { 
… 
! 
def getCollection(db: DefaultDB): BSONCollection = { db.collection(collName) } 
def getBsonForInsert(obj: T): BSONDocument // BSON for insert 
! 
def insertOneAsFuture(db: DefaultDB, obj: T): Future[LastError] = { 
insertOneAsFuture(getCollection(db), obj) 
} 
! 
def insertOneAsFuture(coll: BSONCollection, obj: T): Future[LastError] = { 
coll.insert(getBsonForInsert(obj)) 
} 
… 
}
The Insert 
inside Reactive Mongo GenericCollection 
import reactivemongo.core.netty.BufferSequence 
protected def watchFailure[T](future: => Future[T]): Future[T] = 
Try(future).recover { case e: Throwable => Future.failed(e) }.get 
! 
def insert[T](document: T, writeConcern: GetLastError = GetLastError()) 
(implicit writer: Writer[T], ec: ExecutionContext): Future[LastError] = watchFailure { 
! 
val op = Insert(0, fullCollectionName) 
val bson = writeDoc(document, writer) 
val checkedWriteRequest = CheckedWriteRequest(op, BufferSequence(bson), writeConcern) 
Failover(checkedWriteRequest, db.connection, failoverStrategy).future.mapEither(LastError.meaningful(_)) 
}
Netty in a Nutshell 
Netty architecture in a nutshell - 
http://docs.jboss.org/netty/3.1/guide/html/architecture.html 
• Summary 3 Main Areas: 
• 1. Buffer - ChannelBuffer - Customized types, dynamic sizing 
buffer, faster than ByteBuffer 
• 2. Channel - Universal Asynchronous I/O - abstracts away all 
operations required to point-to-point communication 
(ChannelFactory) 
• 3. Event Model - ChannelEvent, ChannelHandler, ChannelPipeline 
(chain events and send upstream or downstream)
A Tale of 3 Load Tests 
• Non-blocking with ReactiveMongo 
• Blocking with Await on each insert with 
ReactiveMongo 
• Synchronous with Casbah
Load Test 1 
Non-blocking with ReactiveMongo
Load Test 2 
Blocking with ReactiveMongo
Load Test 3 
Synchronous with Casbah
Next Load Tests… 
• Not just inserts. Mongodb is fast at inserts. 
• Heavy Queries 
• Updates
Details: _id 
ObjectId is a 12-byte BSON type, constructed using: 
• a 4-byte value representing the seconds since the Unix epoch, 
• a 3-byte machine identifier, 
• a 2-byte process id, and 
• a 3-byte counter, starting with a random value. 
It is indexed and efficient
Serializing the _id to/from BSON 
object WhaleSighting extends Persistable[WhaleSighting] { 
… 
} 
! 
trait Persistable[T] { 
… 
! 
// MongoId converters 
def getMongoId(doc: BSONDocument, fieldName_id: String): String = { 
val oid: Option[BSONObjectID] = doc.getAs[BSONObjectID](fieldName_id) 
oid match { 
case None => { 
val m = "Failed mongoId conversion for field name " + fieldName_id 
throw new Exception(m) 
case Some(id) => id.stringify // hexadecimal String representation 
} 
} 
def hexStringToMongoId(hexString: String): BSONObjectID = BSONObjectID(hexString) 
! 
… 
}
Find And Modify 
https://github.com/ReactiveMongo/ReactiveMongo/blob/master/driver/samples/ 
SimpleUseCasesSample.scala#L186-212 
// finds all documents with lastName = Godbillon and replace lastName with GODBILLON 
def findAndModify() = { 
val selector = BSONDocument( "lastName" -> "Godbillon") 
val modifier = BSONDocument( "$set" -> BSONDocument("lastName" -> "GODBILLON")) 
val command = FindAndModify(collection.name, selector, Update(modifier, false))! 
db.command(command).onComplete { 
case Failure(error) => { 
throw new RuntimeException("got an error while performing findAndModify", error) 
} 
case Success(maybeDocument) => 
println("findAndModify successfully done with original document = " + 
// if there is an original document returned, print it in a pretty format 
maybeDocument.map(doc => { 
// get a BSONIterator (lazy BSON parser) of this document 
// stringify it with DefaultBSONIterator.pretty 
BSONDocument.pretty(doc) 
})) 
} 
}
Streaming From a Collection 
https://github.com/sgodbillon/reactivemongo-tailablecursor-demo 
def watchCollection = WebSocket.using[JsValue] { request => 
val collection = db.collection[JSONCollection]("acappedcollection") 
// Inserts the received messages into the capped collection 
val in = Iteratee.flatten(futureCollection.map(collection => 
Iteratee.foreach[JsValue] { 
json => println("received " + json) 
collection.insert(json) 
})) 
! 
// Enumerates the capped collection 
val out = { 
val futureEnumerator = futureCollection.map { collection => 
// so we are sure that the collection exists and is a capped one 
val cursor: Cursor[JsValue] = collection 
// we want all the documents 
.find(Json.obj()) 
.options(QueryOpts().tailable.awaitData) // tailable and await data 
.cursor[JsValue] 
cursor.enumerate 
} 
Enumerator.flatten(futureEnumerator) 
} 
! 
// We're done! 
(in, out) 
}
Connections 
http://reactivemongo.org/releases/0.10/documentation/tutorial/connect-database.html 
import reactivemongo.api.MongoDriver 
val driver = new MongoDriver 
//Without any parameter, MongoDriver creates a new Akka’s ActorSystem. 
//Then you can connect to a MongoDB server. 
val connection = driver.connection(List(“localhost")) // a conn pool 
val db = connection.db("somedatabase") 
val collection = db.collection("somecollection")
Play! Thread Pools 
Play uses a number of different thread pools for different purposes: 
• Netty boss/worker thread pools - These are used internally by Netty for handling 
Netty IO. An applications code should never be executed by a thread in these thread 
pools. 
• Play Internal Thread Pool - This is used internally by Play. No application code 
should ever be executed by a thread in this thread pool, and no blocking should ever 
be done in this thread pool. Its size can be configured by setting internal-threadpool-size 
in application.conf, and it defaults to the number of available processors. 
• Play default thread pool - This is the default thread pool in which all application 
code in Play Framework is executed. It is an Akka dispatcher, and can be configured 
by configuring Akka, described below. By default, it has one thread per processor. 
• Akka thread pool - This is used by the Play Akka plugin, and can be configured the 
same way that you would configure Akka.
Relational Database Options? 
https://github.com/mauricio/postgresql-async 
Non-blocking for MySql and PostgreSQL
A tour through the 
code
Data is not information, information is not knowledge, 
knowledge is not understanding, understanding is not 
wisdom. 
! 
- Clifford Stoll 
!

More Related Content

What's hot

Apache Kafka DC Meetup: Replicating DB Binary Logs to Kafka
Apache Kafka DC Meetup: Replicating DB Binary Logs to KafkaApache Kafka DC Meetup: Replicating DB Binary Logs to Kafka
Apache Kafka DC Meetup: Replicating DB Binary Logs to Kafka
Mark Bittmann
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
amix3k
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
Dori Waldman
 
Building a High-Performance Distributed Task Queue on MongoDB
Building a High-Performance Distributed Task Queue on MongoDBBuilding a High-Performance Distributed Task Queue on MongoDB
Building a High-Performance Distributed Task Queue on MongoDBMongoDB
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Tom Croucher
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
Alex Payne
 
Developing High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & GoDeveloping High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & Go
Chris Stivers
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
Alex Miller
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application
Andy Bunce
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
nam kwangjin
 
Play Framework
Play FrameworkPlay Framework
Play Framework
Harinath Krishnamoorthy
 
Storing 16 Bytes at Scale
Storing 16 Bytes at ScaleStoring 16 Bytes at Scale
Storing 16 Bytes at Scale
Fabian Reinartz
 
Real-time streaming and data pipelines with Apache Kafka
Real-time streaming and data pipelines with Apache KafkaReal-time streaming and data pipelines with Apache Kafka
Real-time streaming and data pipelines with Apache Kafka
Joe Stein
 
Robust Operations of Kafka Streams
Robust Operations of Kafka StreamsRobust Operations of Kafka Streams
Robust Operations of Kafka Streams
confluent
 
Jsonnet, terraform & packer
Jsonnet, terraform & packerJsonnet, terraform & packer
Jsonnet, terraform & packer
David Cunningham
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
MongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksScott Hernandez
 
Converting a naive flow to akka streams
Converting a naive flow to akka streamsConverting a naive flow to akka streams
Converting a naive flow to akka streamsGal Topper
 

What's hot (20)

Apache Kafka DC Meetup: Replicating DB Binary Logs to Kafka
Apache Kafka DC Meetup: Replicating DB Binary Logs to KafkaApache Kafka DC Meetup: Replicating DB Binary Logs to Kafka
Apache Kafka DC Meetup: Replicating DB Binary Logs to Kafka
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
Building a High-Performance Distributed Task Queue on MongoDB
Building a High-Performance Distributed Task Queue on MongoDBBuilding a High-Performance Distributed Task Queue on MongoDB
Building a High-Performance Distributed Task Queue on MongoDB
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Developing High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & GoDeveloping High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & Go
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
Storing 16 Bytes at Scale
Storing 16 Bytes at ScaleStoring 16 Bytes at Scale
Storing 16 Bytes at Scale
 
Real-time streaming and data pipelines with Apache Kafka
Real-time streaming and data pipelines with Apache KafkaReal-time streaming and data pipelines with Apache Kafka
Real-time streaming and data pipelines with Apache Kafka
 
Robust Operations of Kafka Streams
Robust Operations of Kafka StreamsRobust Operations of Kafka Streams
Robust Operations of Kafka Streams
 
Jsonnet, terraform & packer
Jsonnet, terraform & packerJsonnet, terraform & packer
Jsonnet, terraform & packer
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
MongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacks
 
Converting a naive flow to akka streams
Converting a naive flow to akka streamsConverting a naive flow to akka streams
Converting a naive flow to akka streams
 

Viewers also liked

Shared Database Concurrency
Shared Database ConcurrencyShared Database Concurrency
Shared Database Concurrency
Aivars Kalvans
 
L12 Concurrent Programming
L12 Concurrent ProgrammingL12 Concurrent Programming
L12 Concurrent Programming
Ólafur Andri Ragnarsson
 
Svetlin Nakov - Database Transactions
Svetlin Nakov - Database TransactionsSvetlin Nakov - Database Transactions
Svetlin Nakov - Database TransactionsSvetlin Nakov
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
Jacob Zvirikuzhe
 
Ch03-Software Engineering Model
Ch03-Software Engineering ModelCh03-Software Engineering Model
Ch03-Software Engineering ModelBala Ganesh
 
Lecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software EngineeringLecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software Engineering
Achmad Solichin
 
1-Introduction to Software Engineering (Object Oriented Software Engineering ...
1-Introduction to Software Engineering (Object Oriented Software Engineering ...1-Introduction to Software Engineering (Object Oriented Software Engineering ...
1-Introduction to Software Engineering (Object Oriented Software Engineering ...
Hafiz Ammar Siddiqui
 
Software process model
Software process modelSoftware process model
Software process model
Muhammad Yousuf Abdul Qadir
 
Lecture 02 Software Process Model
Lecture 02 Software Process ModelLecture 02 Software Process Model
Lecture 02 Software Process Model
Achmad Solichin
 
Waterfall model in Software engineering
Waterfall model in Software engineeringWaterfall model in Software engineering
Waterfall model in Software engineeringEhtesham Mehmood
 
comparison of various sdlc models
comparison of various sdlc modelscomparison of various sdlc models
comparison of various sdlc models
sadaf ateeq
 
Comparison between waterfall model and spiral model
Comparison between waterfall model and spiral modelComparison between waterfall model and spiral model
Comparison between waterfall model and spiral modelGalaxyy Pandey
 
waterfall model
waterfall modelwaterfall model
waterfall model
Shiva Krishna
 
SDLC Model (Waterfall,Iterative Waterfall,Spiral)
SDLC Model (Waterfall,Iterative Waterfall,Spiral)SDLC Model (Waterfall,Iterative Waterfall,Spiral)
SDLC Model (Waterfall,Iterative Waterfall,Spiral)
Shaikh Kamrul Islam (Konok kamrul)
 
Waterfallmodel
WaterfallmodelWaterfallmodel
Waterfallmodel
Sunny Kumar Roy
 
Mongo db
Mongo dbMongo db
Mongo db
Akshay Mathur
 
Waterfall Model
Waterfall ModelWaterfall Model
Spiral model explanation
Spiral model  explanationSpiral model  explanation
Spiral model explanation
Umar Farooq
 
software development, process model, requirement engineering, srs, structured...
software development, process model, requirement engineering, srs, structured...software development, process model, requirement engineering, srs, structured...
software development, process model, requirement engineering, srs, structured...
Ashok Mohanty
 

Viewers also liked (20)

Shared Database Concurrency
Shared Database ConcurrencyShared Database Concurrency
Shared Database Concurrency
 
L12 Concurrent Programming
L12 Concurrent ProgrammingL12 Concurrent Programming
L12 Concurrent Programming
 
Svetlin Nakov - Database Transactions
Svetlin Nakov - Database TransactionsSvetlin Nakov - Database Transactions
Svetlin Nakov - Database Transactions
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Ch03-Software Engineering Model
Ch03-Software Engineering ModelCh03-Software Engineering Model
Ch03-Software Engineering Model
 
Lecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software EngineeringLecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software Engineering
 
1-Introduction to Software Engineering (Object Oriented Software Engineering ...
1-Introduction to Software Engineering (Object Oriented Software Engineering ...1-Introduction to Software Engineering (Object Oriented Software Engineering ...
1-Introduction to Software Engineering (Object Oriented Software Engineering ...
 
Software process model
Software process modelSoftware process model
Software process model
 
Waterfall
WaterfallWaterfall
Waterfall
 
Lecture 02 Software Process Model
Lecture 02 Software Process ModelLecture 02 Software Process Model
Lecture 02 Software Process Model
 
Waterfall model in Software engineering
Waterfall model in Software engineeringWaterfall model in Software engineering
Waterfall model in Software engineering
 
comparison of various sdlc models
comparison of various sdlc modelscomparison of various sdlc models
comparison of various sdlc models
 
Comparison between waterfall model and spiral model
Comparison between waterfall model and spiral modelComparison between waterfall model and spiral model
Comparison between waterfall model and spiral model
 
waterfall model
waterfall modelwaterfall model
waterfall model
 
SDLC Model (Waterfall,Iterative Waterfall,Spiral)
SDLC Model (Waterfall,Iterative Waterfall,Spiral)SDLC Model (Waterfall,Iterative Waterfall,Spiral)
SDLC Model (Waterfall,Iterative Waterfall,Spiral)
 
Waterfallmodel
WaterfallmodelWaterfallmodel
Waterfallmodel
 
Mongo db
Mongo dbMongo db
Mongo db
 
Waterfall Model
Waterfall ModelWaterfall Model
Waterfall Model
 
Spiral model explanation
Spiral model  explanationSpiral model  explanation
Spiral model explanation
 
software development, process model, requirement engineering, srs, structured...
software development, process model, requirement engineering, srs, structured...software development, process model, requirement engineering, srs, structured...
software development, process model, requirement engineering, srs, structured...
 

Similar to Concurrency at the Database Layer

Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lightbend
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
Alex Miller
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with Embulk
Sadayuki Furuhashi
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
Ortus Solutions, Corp
 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
Ortus Solutions, Corp
 
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
HostedbyConfluent
 
Scalable io in java
Scalable io in javaScalable io in java
Scalable io in java
Giridhar Addepalli
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Davorin Vukelic
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
Rob Dunn
 
Level DB - Quick Cheat Sheet
Level DB - Quick Cheat SheetLevel DB - Quick Cheat Sheet
Level DB - Quick Cheat Sheet
Aniruddha Chakrabarti
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
Samantha Quiñones
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
uzquiano
 
Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017
confluent
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
Dev ops meetup
Dev ops meetupDev ops meetup
Dev ops meetup
Bigdata Meetup Kochi
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
bobmcwhirter
 
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Dan Halperin
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
Mirco Vanini
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
bobmcwhirter
 

Similar to Concurrency at the Database Layer (20)

Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with Embulk
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
 
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
 
Scalable io in java
Scalable io in javaScalable io in java
Scalable io in java
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
Level DB - Quick Cheat Sheet
Level DB - Quick Cheat SheetLevel DB - Quick Cheat Sheet
Level DB - Quick Cheat Sheet
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
 
Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Dev ops meetup
Dev ops meetupDev ops meetup
Dev ops meetup
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 

Recently uploaded

AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 

Recently uploaded (20)

AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 

Concurrency at the Database Layer

  • 1. Concurrency at the Database Layer Scala / Reactive Mongo Example For Reactive Programming Enthusiasts Denver Mark Wilson
  • 2. Why ? The Contextual Explanation • To be non-blocking all the way through • Because of Amdahl’s law • and the Reactive Manifesto
  • 3. Amdahl’s Law “…Therefore it is important that the entire solution is asynchronous and non-blocking.” - Reactive Manifesto
  • 4. Reactive • Use resources better to achieve scale, resilience, and performance. • Do this by replacing thread managed state with event-driven messaging • Replace synchronous implementations with non-blocking code. • Pillars: Responsive, Scalable, Event-Driven, Resilient
  • 5.
  • 6. Why (cont.) ? The Specific Explanations for concurrency at the database layer. • Because most db drivers are blocking. • Because concurrency beats thread tuning at large scale. • Because it is faster on multicore machines (which most are) and more fully utilizes the machine recourses
  • 7. Presentation Focus and Outline What I wanted to achieve • Restful services with GET, POST, PUT supported by a concurrent database layer • Demo app resembling a real-world structure • Coding with the library. Example implementation • Some load testing blocking vs non-blocking.
  • 8. Demo Application “Whale Sighting” Single Page application https://github.com/p44/FishStore • The UI ! • The Services ! • The DB Layer
  • 9.
  • 10. The POST POST {"breed":"Sei Whale","count":1,"description":"Pretty whale."}
  • 11. Concurrency with Future(s). So What’s a Future? • A future is an object holding a value that may become available at some point in time. • A future is either completed or not completed • A completed future is either: • Successful(value) • Failed(exception) • A future frees the current thread by establishing a callback
  • 12. Future Example import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} ! val fs: Future[String] = Future { “a” + “b” } fs.onComplete { case Success(x) => println(x) case Failure(e) => throw e } Execution contexts execute tasks submitted to them, and you can think of execution contexts as thread pools.
  • 13. The Insert val fResult: Future[LastError] = WhaleSighting.insertOneAsFuture(db, ws) object WhaleSighting extends Persistable[WhaleSighting] { … } ! trait Persistable[T] { … ! def getCollection(db: DefaultDB): BSONCollection = { db.collection(collName) } def getBsonForInsert(obj: T): BSONDocument // BSON for insert ! def insertOneAsFuture(db: DefaultDB, obj: T): Future[LastError] = { insertOneAsFuture(getCollection(db), obj) } ! def insertOneAsFuture(coll: BSONCollection, obj: T): Future[LastError] = { coll.insert(getBsonForInsert(obj)) } … }
  • 14. The Insert inside Reactive Mongo GenericCollection import reactivemongo.core.netty.BufferSequence protected def watchFailure[T](future: => Future[T]): Future[T] = Try(future).recover { case e: Throwable => Future.failed(e) }.get ! def insert[T](document: T, writeConcern: GetLastError = GetLastError()) (implicit writer: Writer[T], ec: ExecutionContext): Future[LastError] = watchFailure { ! val op = Insert(0, fullCollectionName) val bson = writeDoc(document, writer) val checkedWriteRequest = CheckedWriteRequest(op, BufferSequence(bson), writeConcern) Failover(checkedWriteRequest, db.connection, failoverStrategy).future.mapEither(LastError.meaningful(_)) }
  • 15. Netty in a Nutshell Netty architecture in a nutshell - http://docs.jboss.org/netty/3.1/guide/html/architecture.html • Summary 3 Main Areas: • 1. Buffer - ChannelBuffer - Customized types, dynamic sizing buffer, faster than ByteBuffer • 2. Channel - Universal Asynchronous I/O - abstracts away all operations required to point-to-point communication (ChannelFactory) • 3. Event Model - ChannelEvent, ChannelHandler, ChannelPipeline (chain events and send upstream or downstream)
  • 16. A Tale of 3 Load Tests • Non-blocking with ReactiveMongo • Blocking with Await on each insert with ReactiveMongo • Synchronous with Casbah
  • 17. Load Test 1 Non-blocking with ReactiveMongo
  • 18. Load Test 2 Blocking with ReactiveMongo
  • 19. Load Test 3 Synchronous with Casbah
  • 20. Next Load Tests… • Not just inserts. Mongodb is fast at inserts. • Heavy Queries • Updates
  • 21. Details: _id ObjectId is a 12-byte BSON type, constructed using: • a 4-byte value representing the seconds since the Unix epoch, • a 3-byte machine identifier, • a 2-byte process id, and • a 3-byte counter, starting with a random value. It is indexed and efficient
  • 22. Serializing the _id to/from BSON object WhaleSighting extends Persistable[WhaleSighting] { … } ! trait Persistable[T] { … ! // MongoId converters def getMongoId(doc: BSONDocument, fieldName_id: String): String = { val oid: Option[BSONObjectID] = doc.getAs[BSONObjectID](fieldName_id) oid match { case None => { val m = "Failed mongoId conversion for field name " + fieldName_id throw new Exception(m) case Some(id) => id.stringify // hexadecimal String representation } } def hexStringToMongoId(hexString: String): BSONObjectID = BSONObjectID(hexString) ! … }
  • 23. Find And Modify https://github.com/ReactiveMongo/ReactiveMongo/blob/master/driver/samples/ SimpleUseCasesSample.scala#L186-212 // finds all documents with lastName = Godbillon and replace lastName with GODBILLON def findAndModify() = { val selector = BSONDocument( "lastName" -> "Godbillon") val modifier = BSONDocument( "$set" -> BSONDocument("lastName" -> "GODBILLON")) val command = FindAndModify(collection.name, selector, Update(modifier, false))! db.command(command).onComplete { case Failure(error) => { throw new RuntimeException("got an error while performing findAndModify", error) } case Success(maybeDocument) => println("findAndModify successfully done with original document = " + // if there is an original document returned, print it in a pretty format maybeDocument.map(doc => { // get a BSONIterator (lazy BSON parser) of this document // stringify it with DefaultBSONIterator.pretty BSONDocument.pretty(doc) })) } }
  • 24. Streaming From a Collection https://github.com/sgodbillon/reactivemongo-tailablecursor-demo def watchCollection = WebSocket.using[JsValue] { request => val collection = db.collection[JSONCollection]("acappedcollection") // Inserts the received messages into the capped collection val in = Iteratee.flatten(futureCollection.map(collection => Iteratee.foreach[JsValue] { json => println("received " + json) collection.insert(json) })) ! // Enumerates the capped collection val out = { val futureEnumerator = futureCollection.map { collection => // so we are sure that the collection exists and is a capped one val cursor: Cursor[JsValue] = collection // we want all the documents .find(Json.obj()) .options(QueryOpts().tailable.awaitData) // tailable and await data .cursor[JsValue] cursor.enumerate } Enumerator.flatten(futureEnumerator) } ! // We're done! (in, out) }
  • 25. Connections http://reactivemongo.org/releases/0.10/documentation/tutorial/connect-database.html import reactivemongo.api.MongoDriver val driver = new MongoDriver //Without any parameter, MongoDriver creates a new Akka’s ActorSystem. //Then you can connect to a MongoDB server. val connection = driver.connection(List(“localhost")) // a conn pool val db = connection.db("somedatabase") val collection = db.collection("somecollection")
  • 26. Play! Thread Pools Play uses a number of different thread pools for different purposes: • Netty boss/worker thread pools - These are used internally by Netty for handling Netty IO. An applications code should never be executed by a thread in these thread pools. • Play Internal Thread Pool - This is used internally by Play. No application code should ever be executed by a thread in this thread pool, and no blocking should ever be done in this thread pool. Its size can be configured by setting internal-threadpool-size in application.conf, and it defaults to the number of available processors. • Play default thread pool - This is the default thread pool in which all application code in Play Framework is executed. It is an Akka dispatcher, and can be configured by configuring Akka, described below. By default, it has one thread per processor. • Akka thread pool - This is used by the Play Akka plugin, and can be configured the same way that you would configure Akka.
  • 27. Relational Database Options? https://github.com/mauricio/postgresql-async Non-blocking for MySql and PostgreSQL
  • 28. A tour through the code
  • 29. Data is not information, information is not knowledge, knowledge is not understanding, understanding is not wisdom. ! - Clifford Stoll !