SlideShare a Scribd company logo
1 of 37
Download to read offline
Async Microservices 
with Finagle 
Vladimir Kostyukov 
http://vkostyukov.ru
Asynchronous 
Protocol-Agnostic 
Full-Stack RPC 
2
Adopters 
3
Built atop of Netty 
(#1 Non-Blocking I/O for JVM) 
4
Finagle - 
Netty in a functional setting 
5
Building Blocks: 
Services + Futures + Filters 
6
trait Service[-Req, +Rep] extends (Req => Future[Rep]) 
7
Service-Oriented 
rather then 
Stream-Oriented 
8
// TODO: Don't forget to remove it in production. 
object GetDeveloperPromotionDate extends Service[Developer, Date] { 
def apply(req: Developer) = Future.never 
} 
val date: Future[Date] = GetDeveloperPromotionDate(Developer.Myself) 
9
1 val respond = new Service[HttpRequest, HttpResponse] { 
2 def apply(req: HttpRequest) = { 
3 val rep = new DefaultHttpResponse(HttpVersion.HTTP_1_1, 
4 HttpResponseStatus.OK) 
5 rep.setContentString(req.getUri()) 
6 Future.value(rep) 
7 } 
8 } 
9 
10 Await.ready(Http.serve(":8080", respond) 
10
Servers and Clients 
talk to each other via services 
11
1 val to = Http.newService("google.com") 
2 
3 val proxy = new Service[HttpRequest, HttpResponse] { 
4 def apply(req: HttpRequest) = to(req) 
5 } 
6 
7 Await.ready(Http.serve(":8080", proxy) 
12
Are there high-order services? 
13
14 
Client 
Service 
Server 
Filter Filter Filter Service
// ReqIn -> Service(ReqOut -> RepIn) -> RepOut 
trait Filter[-ReqIn, +RepOut, +ReqOut, -RepIn] 
extends ((ReqIn, Service[ReqOut, RepIn]) => Future[RepOut]) 
15
// A filter that does nothing. 
def identity[Req, Rep] = new Filter[Req, Rep, Req, Rep] { 
def apply(req: Req, service: Service[Req, Rep]) = service(req) 
} 
val auth = identity[HttpRequest, HttpResponse] 
16
Filters are type-safe! 
17
A Type-Safe Input Filter 
1 object TurnAIntoB extends Filter[A, Rep, B, Rep] { 
2 def apply(req: A, service: Service[B, Rep]): Future[Rep] = 
3 service(req.toB) 
4 } 
5 
6 val serviceOfB: Service[B, Rep] = ... 
7 val serviceOfA: Service[A, Rep] = TurnAIntoB andThen serviceOfA 
18
A Type-Safe Output Filter 
1 object TurnAIntoB extends Filter[Req, B, Req, A] { 
2 def apply(req: Req, service: Service[Req, A]): Future[B] = 
3 service(req) map { a => a.toB } 
4 } 
5 
6 val serviceOfA: Service[Req, A] = ... 
7 val serviceOfB: Service[Req, B] = TurnAIntoB andThen serviceOfA 
19
Case Study: TimeOut Filter 
1 def timeout[Req, Rep](timeout: Duration)(implicit timer: Timer) = 
2 new SimpleFilter[Req, Rep] { 
3 def apply(req: Req, service: Service[Req, Rep]) = 
4 service(req).within(timer, timeout) 
5 } 
6 
7 val handleExceptions = new SimpleFilter[Req, Rep] { 
8 def apply(req: Req, service: Service[Req, Rep]) = 
9 service(req) handle { 
10 case t: TimeOutException => Future.value(defaultRep) 
11 } 
12 } 
13 
14 val respond = new Service[Req, Rep] { ... } 
15 // We guarantee 3 seconds response time. 
16 val backend = handleExceptions andThen 
17 timeout(3.seconds) andThen 
18 respond 
20
Case Study: OAuth2Filter 
1 class OAuth2Filter[U](dataHandler: DataHandler[U]) 
2 extends Filter[HttpRequest, HttpResponse, OAuth2Request[U], HttpResponse] 
3 with OAuth2 with OAuthErrorHandler { 
4 
5 def handleError(e: OAuthError) = e.toHttpResponse 
6 def apply(req: HttpRequest, service: Service[OAuth2Request[U], HttpResponse]) = 
7 authorize(req, dataHandler) flatMap { authInfo => 
8 service(OAuth2Request(authInfo, req)) 
9 } handle { 
10 case e: OAuthError => handleError(e) 
11 } 
12 } 
13 
14 val authorize = new OAuth2Filter(...) 
15 val respond: Service[OAuth2Request[U], HttpResponse] = ??? 
16 val backend: Service[HttpRequest, HttpResponse] = authorize andThen respond 
21
Future is a monad! 
22
Abstraction: Fibonacci Calculator 
1 trait FibonacciCalculator { 
2 val Zero = BigInt(0) 
3 val One = BigInt(1) 
4 val Two = BigInt(2) 
5 
6 def calculate(n: BigInt): Future[BigInt] 
7 } 
23
Sequential Composition: map & flatMap 
1 trait Future[+A] { 
2 def flatMap[B](f: A => Future[B]): Future[B] 
3 def map[B](f: A => B): Future[B] 
4 } 
24
FlatMap Power 
1 val ab: Service[A, B] = ??? 
2 val bc: Service[B, C] = ??? 
3 val cd: Service[C, D] = ??? 
4 
5 val req: A = ??? 
6 val rep: Future[D] = ab(req) flatMap bc flatMap cd 
25
Sequential Composition: map & flatMap 
1 object FlatMapFibonacciCalculator extends FibonacciCalculator { 
2 def calculate(n: BigInt): Future[BigInt] = 
3 if (n == Zero || n == One) Future.value(n) 
4 else calculate(n - One) flatMap { a => 
5 calculate(n - Two) flatMap { b => Future.value(a + b) } 
6 } 
7 } 
8 
9 object MapFibonacciCalculator extends FibonacciCalculator { 
10 def calculate(n: BigInt): Future[BigInt] = 
11 if (n == Zero || n == One) Future.value(n) 
12 else calculate(n - One) map { a => 
13 calculate(n - Two) map { b => a + b } 
14 } 
15 } 
26
Sequential Composition: for-comprehension 
1 object ForFibonacciCalculator extends FibonacciCalculator { 
2 def calculate(n: BigInt): Future[BigInt] = 
3 if (n == Zero || n == One) Future.value(n) 
4 else for { 
5 a <- calculate(n - One) 
6 b <- calculate(n - Two) 
7 } yield a + b 
8 } 
27
Concurrent Composition: collect & select 
1 object Future { 
2 def collect[A](fs: Seq[Future[A]]): Future[Seq[A]] 
3 def select[A](fs: Seq[Future[A]]): Future[A] 
4 } 
28
Concurrent Composition: collect 
1 class FanoutFibonacciCalculator( 
2 left: FibonacciCalculator, 
3 right: FibonacciCalculator) extends FibonacciCalculator { 
4 
5 def calculate(n: BigInt): Future[BigInt] = 
6 if (n == Zero) || n == One) Future.value(n) 
7 else { 
8 val seq = Seq(left.calculate(n - One), right.calculate(n - Two)) 
9 Future.collect(seq) map { _.sum } 
10 } 
11 } 
29
Concurrent Composition: select 
1 class SelectFibonacciCalculator(seq: Seq[FibonacciCalculator]) 
2 extends FibonacciCalculator { 
3 
4 def calculate(n: BigInt): Future[BigInt] = { 
5 val futures: Seq[Future[BigInt]] = seq map { _.calculate(n) } 
6 Future.select(futures) 
7 } 
8 } 
30
Futures should be 
chained asynchronously 
31
Do Not Await 
// Asynchronous operation. 
val f = service(req) 
// Blocking operation. 
Await.result(f) 
32
Involving Side-Effects 
// Asynchronous operation. 
val f = service(req) 
! 
f onSuccess { rep => println("Got the value: " + rep) } 
onFailure { t => t.printStackTrace() } 
33
Finagle is a non-blocking glue for 
services that implement 
different protocols 
34
Finagle is extremely good at 
gluing things that work 
with different speed 
35
References 
§ http://twitter.github.io/finagle/ 
! 
§ http://vkostyukov.ru/posts/finagle-your-fibonacci-calculation/ 
! 
§ https://github.com/finagle/finch 
! 
§ https://github.com/finagle/finagle-oauth2 
36
Stay Finagled! 
! 
And drop your feedbacks to 
@vkostyukov 
37

More Related Content

What's hot

2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.jsNoritada Shimizu
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloadingRai University
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++Bharat Kalia
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob LisiUsing Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob LisiInfluxData
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentBadoo Development
 
Compositional I/O Stream in Scala
Compositional I/O Stream in ScalaCompositional I/O Stream in Scala
Compositional I/O Stream in ScalaC4Media
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185Mahmoud Samir Fayed
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲームNoritada Shimizu
 

What's hot (20)

Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
20151224-games
20151224-games20151224-games
20151224-games
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 
Graphql with Flamingo
Graphql with FlamingoGraphql with Flamingo
Graphql with Flamingo
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Queue oop
Queue   oopQueue   oop
Queue oop
 
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob LisiUsing Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
Using Grafana with InfluxDB 2.0 and Flux Lang by Jacob Lisi
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
 
Compositional I/O Stream in Scala
Compositional I/O Stream in ScalaCompositional I/O Stream in Scala
Compositional I/O Stream in Scala
 
Source Plugins
Source PluginsSource Plugins
Source Plugins
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181
 
Introduction to Go for Java Programmers
Introduction to Go for Java ProgrammersIntroduction to Go for Java Programmers
Introduction to Go for Java Programmers
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 

Viewers also liked

High Performance RPC with Finagle
High Performance RPC with FinagleHigh Performance RPC with Finagle
High Performance RPC with FinagleSamir Bessalah
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices💡 Tomasz Kogut
 
Service Objects Evolution
Service Objects EvolutionService Objects Evolution
Service Objects EvolutionAbdriy Mosin
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaMax Alexejev
 
A sane approach to microservices
A sane approach to microservicesA sane approach to microservices
A sane approach to microservicesToby Matejovsky
 
Finagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloudFinagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloudPhil Calçado
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Legacy Typesafe (now Lightbend)
 
The end of polling : why and how to transform a REST API into a Data Streamin...
The end of polling : why and how to transform a REST API into a Data Streamin...The end of polling : why and how to transform a REST API into a Data Streamin...
The end of polling : why and how to transform a REST API into a Data Streamin...Audrey Neveu
 
Spring Cloud Netflixを使おう #jsug
Spring Cloud Netflixを使おう #jsugSpring Cloud Netflixを使おう #jsug
Spring Cloud Netflixを使おう #jsugToshiaki Maki
 
ELK at LinkedIn - Kafka, scaling, lessons learned
ELK at LinkedIn - Kafka, scaling, lessons learnedELK at LinkedIn - Kafka, scaling, lessons learned
ELK at LinkedIn - Kafka, scaling, lessons learnedTin Le
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 

Viewers also liked (18)

High Performance RPC with Finagle
High Performance RPC with FinagleHigh Performance RPC with Finagle
High Performance RPC with Finagle
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Finatra v2
Finatra v2Finatra v2
Finatra v2
 
Ember vs Backbone
Ember vs BackboneEmber vs Backbone
Ember vs Backbone
 
Service Objects Evolution
Service Objects EvolutionService Objects Evolution
Service Objects Evolution
 
Rabbitmq basics
Rabbitmq basicsRabbitmq basics
Rabbitmq basics
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and Scala
 
Scala.io
Scala.ioScala.io
Scala.io
 
A sane approach to microservices
A sane approach to microservicesA sane approach to microservices
A sane approach to microservices
 
Numba Overview
Numba OverviewNumba Overview
Numba Overview
 
Finagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloudFinagle-Based Microservices at SoundCloud
Finagle-Based Microservices at SoundCloud
 
Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)Reactive Streams 1.0.0 and Why You Should Care (webinar)
Reactive Streams 1.0.0 and Why You Should Care (webinar)
 
The end of polling : why and how to transform a REST API into a Data Streamin...
The end of polling : why and how to transform a REST API into a Data Streamin...The end of polling : why and how to transform a REST API into a Data Streamin...
The end of polling : why and how to transform a REST API into a Data Streamin...
 
Spring Cloud Netflixを使おう #jsug
Spring Cloud Netflixを使おう #jsugSpring Cloud Netflixを使おう #jsug
Spring Cloud Netflixを使おう #jsug
 
Think Async in Java 8
Think Async in Java 8Think Async in Java 8
Think Async in Java 8
 
Cyansible
CyansibleCyansible
Cyansible
 
ELK at LinkedIn - Kafka, scaling, lessons learned
ELK at LinkedIn - Kafka, scaling, lessons learnedELK at LinkedIn - Kafka, scaling, lessons learned
ELK at LinkedIn - Kafka, scaling, lessons learned
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 

Similar to Async Microservices with Twitter's Finagle

Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Finagle Lightning Talk JPR 2014
Finagle Lightning Talk JPR 2014Finagle Lightning Talk JPR 2014
Finagle Lightning Talk JPR 2014Chris Phelps
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器vito jeng
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin HuaiA Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin HuaiDatabricks
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Functional Programming from OO perspective (Sayeret Lambda lecture)
Functional Programming from OO perspective (Sayeret Lambda lecture)Functional Programming from OO perspective (Sayeret Lambda lecture)
Functional Programming from OO perspective (Sayeret Lambda lecture)Ittay Dror
 
A practical work of matlab
A practical work of matlabA practical work of matlab
A practical work of matlabSalanSD
 
Functional Systems @ Twitter
Functional Systems @ TwitterFunctional Systems @ Twitter
Functional Systems @ TwitterC4Media
 
科特林λ學
科特林λ學科特林λ學
科特林λ學彥彬 洪
 
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensionsOleksandr Zhevzhyk
 

Similar to Async Microservices with Twitter's Finagle (20)

Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Finagle Lightning Talk JPR 2014
Finagle Lightning Talk JPR 2014Finagle Lightning Talk JPR 2014
Finagle Lightning Talk JPR 2014
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin HuaiA Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
A Deep Dive into Spark SQL's Catalyst Optimizer with Yin Huai
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Functional Programming from OO perspective (Sayeret Lambda lecture)
Functional Programming from OO perspective (Sayeret Lambda lecture)Functional Programming from OO perspective (Sayeret Lambda lecture)
Functional Programming from OO perspective (Sayeret Lambda lecture)
 
A practical work of matlab
A practical work of matlabA practical work of matlab
A practical work of matlab
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Functional Systems @ Twitter
Functional Systems @ TwitterFunctional Systems @ Twitter
Functional Systems @ Twitter
 
科特林λ學
科特林λ學科特林λ學
科特林λ學
 
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Async Microservices with Twitter's Finagle

  • 1. Async Microservices with Finagle Vladimir Kostyukov http://vkostyukov.ru
  • 4. Built atop of Netty (#1 Non-Blocking I/O for JVM) 4
  • 5. Finagle - Netty in a functional setting 5
  • 6. Building Blocks: Services + Futures + Filters 6
  • 7. trait Service[-Req, +Rep] extends (Req => Future[Rep]) 7
  • 8. Service-Oriented rather then Stream-Oriented 8
  • 9. // TODO: Don't forget to remove it in production. object GetDeveloperPromotionDate extends Service[Developer, Date] { def apply(req: Developer) = Future.never } val date: Future[Date] = GetDeveloperPromotionDate(Developer.Myself) 9
  • 10. 1 val respond = new Service[HttpRequest, HttpResponse] { 2 def apply(req: HttpRequest) = { 3 val rep = new DefaultHttpResponse(HttpVersion.HTTP_1_1, 4 HttpResponseStatus.OK) 5 rep.setContentString(req.getUri()) 6 Future.value(rep) 7 } 8 } 9 10 Await.ready(Http.serve(":8080", respond) 10
  • 11. Servers and Clients talk to each other via services 11
  • 12. 1 val to = Http.newService("google.com") 2 3 val proxy = new Service[HttpRequest, HttpResponse] { 4 def apply(req: HttpRequest) = to(req) 5 } 6 7 Await.ready(Http.serve(":8080", proxy) 12
  • 13. Are there high-order services? 13
  • 14. 14 Client Service Server Filter Filter Filter Service
  • 15. // ReqIn -> Service(ReqOut -> RepIn) -> RepOut trait Filter[-ReqIn, +RepOut, +ReqOut, -RepIn] extends ((ReqIn, Service[ReqOut, RepIn]) => Future[RepOut]) 15
  • 16. // A filter that does nothing. def identity[Req, Rep] = new Filter[Req, Rep, Req, Rep] { def apply(req: Req, service: Service[Req, Rep]) = service(req) } val auth = identity[HttpRequest, HttpResponse] 16
  • 18. A Type-Safe Input Filter 1 object TurnAIntoB extends Filter[A, Rep, B, Rep] { 2 def apply(req: A, service: Service[B, Rep]): Future[Rep] = 3 service(req.toB) 4 } 5 6 val serviceOfB: Service[B, Rep] = ... 7 val serviceOfA: Service[A, Rep] = TurnAIntoB andThen serviceOfA 18
  • 19. A Type-Safe Output Filter 1 object TurnAIntoB extends Filter[Req, B, Req, A] { 2 def apply(req: Req, service: Service[Req, A]): Future[B] = 3 service(req) map { a => a.toB } 4 } 5 6 val serviceOfA: Service[Req, A] = ... 7 val serviceOfB: Service[Req, B] = TurnAIntoB andThen serviceOfA 19
  • 20. Case Study: TimeOut Filter 1 def timeout[Req, Rep](timeout: Duration)(implicit timer: Timer) = 2 new SimpleFilter[Req, Rep] { 3 def apply(req: Req, service: Service[Req, Rep]) = 4 service(req).within(timer, timeout) 5 } 6 7 val handleExceptions = new SimpleFilter[Req, Rep] { 8 def apply(req: Req, service: Service[Req, Rep]) = 9 service(req) handle { 10 case t: TimeOutException => Future.value(defaultRep) 11 } 12 } 13 14 val respond = new Service[Req, Rep] { ... } 15 // We guarantee 3 seconds response time. 16 val backend = handleExceptions andThen 17 timeout(3.seconds) andThen 18 respond 20
  • 21. Case Study: OAuth2Filter 1 class OAuth2Filter[U](dataHandler: DataHandler[U]) 2 extends Filter[HttpRequest, HttpResponse, OAuth2Request[U], HttpResponse] 3 with OAuth2 with OAuthErrorHandler { 4 5 def handleError(e: OAuthError) = e.toHttpResponse 6 def apply(req: HttpRequest, service: Service[OAuth2Request[U], HttpResponse]) = 7 authorize(req, dataHandler) flatMap { authInfo => 8 service(OAuth2Request(authInfo, req)) 9 } handle { 10 case e: OAuthError => handleError(e) 11 } 12 } 13 14 val authorize = new OAuth2Filter(...) 15 val respond: Service[OAuth2Request[U], HttpResponse] = ??? 16 val backend: Service[HttpRequest, HttpResponse] = authorize andThen respond 21
  • 22. Future is a monad! 22
  • 23. Abstraction: Fibonacci Calculator 1 trait FibonacciCalculator { 2 val Zero = BigInt(0) 3 val One = BigInt(1) 4 val Two = BigInt(2) 5 6 def calculate(n: BigInt): Future[BigInt] 7 } 23
  • 24. Sequential Composition: map & flatMap 1 trait Future[+A] { 2 def flatMap[B](f: A => Future[B]): Future[B] 3 def map[B](f: A => B): Future[B] 4 } 24
  • 25. FlatMap Power 1 val ab: Service[A, B] = ??? 2 val bc: Service[B, C] = ??? 3 val cd: Service[C, D] = ??? 4 5 val req: A = ??? 6 val rep: Future[D] = ab(req) flatMap bc flatMap cd 25
  • 26. Sequential Composition: map & flatMap 1 object FlatMapFibonacciCalculator extends FibonacciCalculator { 2 def calculate(n: BigInt): Future[BigInt] = 3 if (n == Zero || n == One) Future.value(n) 4 else calculate(n - One) flatMap { a => 5 calculate(n - Two) flatMap { b => Future.value(a + b) } 6 } 7 } 8 9 object MapFibonacciCalculator extends FibonacciCalculator { 10 def calculate(n: BigInt): Future[BigInt] = 11 if (n == Zero || n == One) Future.value(n) 12 else calculate(n - One) map { a => 13 calculate(n - Two) map { b => a + b } 14 } 15 } 26
  • 27. Sequential Composition: for-comprehension 1 object ForFibonacciCalculator extends FibonacciCalculator { 2 def calculate(n: BigInt): Future[BigInt] = 3 if (n == Zero || n == One) Future.value(n) 4 else for { 5 a <- calculate(n - One) 6 b <- calculate(n - Two) 7 } yield a + b 8 } 27
  • 28. Concurrent Composition: collect & select 1 object Future { 2 def collect[A](fs: Seq[Future[A]]): Future[Seq[A]] 3 def select[A](fs: Seq[Future[A]]): Future[A] 4 } 28
  • 29. Concurrent Composition: collect 1 class FanoutFibonacciCalculator( 2 left: FibonacciCalculator, 3 right: FibonacciCalculator) extends FibonacciCalculator { 4 5 def calculate(n: BigInt): Future[BigInt] = 6 if (n == Zero) || n == One) Future.value(n) 7 else { 8 val seq = Seq(left.calculate(n - One), right.calculate(n - Two)) 9 Future.collect(seq) map { _.sum } 10 } 11 } 29
  • 30. Concurrent Composition: select 1 class SelectFibonacciCalculator(seq: Seq[FibonacciCalculator]) 2 extends FibonacciCalculator { 3 4 def calculate(n: BigInt): Future[BigInt] = { 5 val futures: Seq[Future[BigInt]] = seq map { _.calculate(n) } 6 Future.select(futures) 7 } 8 } 30
  • 31. Futures should be chained asynchronously 31
  • 32. Do Not Await // Asynchronous operation. val f = service(req) // Blocking operation. Await.result(f) 32
  • 33. Involving Side-Effects // Asynchronous operation. val f = service(req) ! f onSuccess { rep => println("Got the value: " + rep) } onFailure { t => t.printStackTrace() } 33
  • 34. Finagle is a non-blocking glue for services that implement different protocols 34
  • 35. Finagle is extremely good at gluing things that work with different speed 35
  • 36. References § http://twitter.github.io/finagle/ ! § http://vkostyukov.ru/posts/finagle-your-fibonacci-calculation/ ! § https://github.com/finagle/finch ! § https://github.com/finagle/finagle-oauth2 36
  • 37. Stay Finagled! ! And drop your feedbacks to @vkostyukov 37