SlideShare a Scribd company logo
Distributing Systems in Scala
with Finagle
Julio Capote
About me
•
•
•

Julio Capote
API team at Twitter
@capotej
This talk
•
•
•
•

Services
Scala
Finagle
Examples
Scaling
Julio Capote, Twitter
Julio Capote, Twitter
Julio Capote, Twitter
Julio Capote, Twitter
Julio Capote, Twitter
Monolithic System
•
•
•

Limited to a single language and runtime
Can only support few developers
Deploys get more dangerous
Solution?
Julio Capote, Twitter
Julio Capote, Twitter
Distributed System
•
•
•

Each service written in appropriate language
Can only support many developers
Granular deploys
But, this is complex...
Julio Capote, Twitter
Julio Capote, Twitter
Julio Capote, Twitter
Quick Scala Intro
What is Scala?
•
•
•
•

JVM language
Interoperable with Java
Functional
But Object Oriented too
Values
val foo: String = "bar"
val age: Int = 27
Type inference
val foo = "bar"
val foo: String = "bar"
Collections
List(61,31,34)
Seq(1,2,3)
Dictionaries / Hashes
Map("foo" -> "bar")
Functional
val addOne =
{ x: Int => x + 1 }
addOne.apply(2) => 3
addOne(2) => 3
val list = Seq(1,2,3,4)
list.map { x => addOne(x) }
list.map(addOne(_))
list.map(addOne)
list map(addOne)
list map addOne
list map addOne filter
{ item: Int =>
item % 2 == 0 }
Function Composition
val addOne =
{ x: Int => x + 1 }
val addTwo =
{ x: Int => x + 2 }
val addThree =
addOne compose addTwo
val addOne =
{ x: Int => x + 1 }
val addTwo =
{ x: Int => x + 2 }
val addThree =
addOne compose addTwo
addThree(2) => 5
Object oriented
class Dog extends Animal
def bark = {
println("woof")
}
}
Options
Julio Capote, Twitter
Map("foo" -> "bar").get("foo")
Some(bar)
Map("foo" -> "bar").get("zzz")
None
val a = Map("foo" -> "bar")
val opt = a.get("zzz")

val result =
opt.getOrElse("default")
val a = Map("foo" -> "bar")
val opt = a.get("zzz")
val result = opt match {
case Some(x) => x
case None => "default"
}
val a = Map("foo" -> "bar")
val opt = a.get("zzz")
opt foreach { result =>
println(result)
}
Finagle
What is Finagle?
•
•
•
•

Client/Server RPC Framework
Asynchronous
Functional
Protocol Agnostic
Futures
Julio Capote, Twitter
Julio Capote, Twitter
Julio Capote, Twitter
Julio Capote, Twitter
def fetchUrl(url: String) = Future[Response]
val f: Future[Response] =
fetchUrl("google.ru")

f map { response =>
println(response.content)
}
val f: Future[Response] =
fetchUrl("google.ru")

f onSuccess { response =>
println(response.content)
} onFailure {
case e => log.error(e)
}
val f: Future[Response] =
fetchUrl("google.ru")

f onSuccess { response =>
println(response.content)
} onFailure {
case e => log.error(e)
}
Services
“Your Server as a Function”
type Service[Req, Rep] = Req => Future[Rep]
Request => Future[Response]
Julio Capote, Twitter
Http Client
val client: Service[Request, Response] =
Http.newService("www.google.ru:80")
Making a request
val req = Request("/")
client(req) onSuccess { resp =>
println(resp.content)
}
val req = Request("/")
client.apply(req) onSuccess { resp =>
println(resp.content)
}
val req = Request("/")
val resp = client(req)
resp onSuccess { resp =>
println(resp.content)
}

Await.ready(resp)
val req = Request("/")
val resp = client(req)
resp onSuccess { resp =>
println(resp.content)
}

Await.ready(resp)
Http Server
class MyServer
extends Service[Request, Response] {
def apply(request: Request) = {
Future.value(new Response("hi"))
}
}
class MyServer
extends Service[Request, Response] {
def apply(request: Request) = {
Future.value(new Response("hi"))
}
}
Request => Future[Response]
Starting the server
val service = new MyServer
val server = Http.serve(":8080", service)
Await.ready(server)
Http Proxy
object Proxy extends App {
val client: Service[Request, Response] =
Http.newService("www.google.ru:80")
val server = Http.serve(":8080", client)

Await.ready(server)
}
object Proxy extends App {
val client: Service[Request, Response] =
Http.newService("www.google.ru:80")
val server = Http.serve(":8080", client)

Await.ready(server)
}
object Proxy extends App {
val client: Service[Request, Response] =
Http.newService("www.google.ru:80")
val server = Http.serve(":8080", client)

Await.ready(server)
}
Filters
Julio Capote, Twitter
Filter[InRequest,
InResponse,
OutRequest,
OutResponse]
Filter[InRequest,
InResponse,
OutRequest,
OutResponse]
Filter[InRequest,
InResponse,
OutRequest,
OutResponse]
SimpleFilter[Request, Response]
def apply(request: Req,
service: Service[Req, Rep]): Future[Rep]
def apply(request: Req,
service: Service[Req, Rep]): Future[Rep]
def apply(request: Req,
service: Service[Req, Rep]): Future[Rep]
def apply(request: Req,
service: Service[Req, Rep]): Future[Rep]
class ScreamFilter[Req, Rep]
extends SimpleFilter[Req, Rep]
def apply(request: Req,
service: Service[Req, Rep]) = {
service(request) onSuccess { response =>
response.setContent(response.content + "!")
response
}
}

}
class ScreamFilter[Req, Rep]
extends SimpleFilter[Req, Rep]
def apply(request: Req,
service: Service[Req, Rep]) = {
service(request) onSuccess { response =>
response.setContent(response.content + "!")
response
}
}

}
class ScreamFilter[Req, Rep]
extends SimpleFilter[Req, Rep]
def apply(request: Req,
service: Service[Req, Rep]) = {
service(request) onSuccess { response =>
response.setContent(response.content + "!")
response
}
}

}
class ScreamFilter[Req, Rep]
extends SimpleFilter[Req, Rep]
def apply(request: Req,
service: Service[Req, Rep]) = {
service(request) onSuccess { response =>
response.setContent(response.content + "!")
response
}
}

}
class ScreamFilter[Req, Rep]
extends SimpleFilter[Req, Rep]
def apply(request: Req,
service: Service[Req, Rep]) = {
service(request) onSuccess { response =>
response.setContent(response.content + "!")
response
}
}

}
class ScreamFilter[Req, Rep]
extends SimpleFilter[Req, Rep]
def apply(request: Req,
service: Service[Req, Rep]) = {
service(request) onSuccess { response =>
response.setContent(response.content + "!")
response
}
}

}
val service = new MyServer
val server = Http.serve(":8080", service)
Await.ready(server)
val service = new MyServer
val myFilter = new MyFilter
val newService = myFilter andThen service
val server = Http.serve(":8080", newService)
Await.ready(server)
val service = new MyServer
val myFilter = new MyFilter
val newService = myFilter andThen service
val server = Http.serve(":8080", newService)
Await.ready(server)
val service = new MyServer
val myFilter = new MyFilter
val newService = myFilter andThen service
val server = Http.serve(":8080", newService)
Await.ready(server)
Metrics
Julio Capote, Twitter
curl http://localhost:9990/admin/metrics.json
Julio Capote, Twitter
Add your own
class MyServer(stats: StatsReceiver)
extends Service[Request, Response] {
def apply(request: Request) = {
stats.counter("my counter").incr()
stats.time("fetch") {
expensiveOperation()
}

Future.value(new Response("hi"))
}
}
class MyServer(stats: StatsReceiver)
extends Service[Request, Response] {
def apply(request: Request) = {
stats.counter("my counter").incr()
stats.time("fetch") {
expensiveOperation()
}

Future.value(new Response("hi"))
}
}
class MyServer(stats: StatsReceiver)
extends Service[Request, Response] {
def apply(request: Request) = {
stats.counter("my counter").incr()
stats.time("fetch") {
expensiveOperation()
}

Future.value(new Response("hi"))
}
}
Finatra
Finagle with Sinatra
class Example extends Controller {
get("/") { request =>
render.plain("hi").toFuture
}
}
class Example extends Controller {
get("/") { request =>
render.plain("hi").toFuture
}
}
class MyServer extends FinatraServer {
val controller = new Example()
register(controller)
}
http://finatra.info
Questions?
•
•
•
•

http://tinyurl.com/finagle-guide
http://tinyurl.com/server-as-a-function
http://finatra.info
@capotej

More Related Content

PDF
API first with Swagger and Scala by Slava Schmidt
PDF
A Blueprint for Scala Microservices
PDF
PHP 8.1 - What's new and changed
PDF
Scala: Functioneel programmeren in een object georiënteerde wereld
PPTX
An introduction to scala
PDF
The Ring programming language version 1.6 book - Part 42 of 189
KEY
Getting the most out of Java [Nordic Coding-2010]
PDF
Scala in Places API
API first with Swagger and Scala by Slava Schmidt
A Blueprint for Scala Microservices
PHP 8.1 - What's new and changed
Scala: Functioneel programmeren in een object georiënteerde wereld
An introduction to scala
The Ring programming language version 1.6 book - Part 42 of 189
Getting the most out of Java [Nordic Coding-2010]
Scala in Places API

What's hot (20)

PPTX
Sharding and Load Balancing in Scala - Twitter's Finagle
PDF
Java 8: the good parts!
PDF
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
PDF
[QE 2018] Łukasz Gawron – Testing Batch and Streaming Spark Applications
PPTX
Exploring Streams and Lambdas in Java8
PDF
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
PDF
Scala @ TechMeetup Edinburgh
KEY
Djangocon
TXT
An a z index of windows power shell commandss
PPTX
Java8lambda
KEY
RIAs Done Right: Grails, Flex, and EXT GWT
PDF
The Steel industry, Elixir, PostgreSQL & file_fdw
PDF
Linked to ArrayList: the full story
PPTX
Scale up your thinking
ODP
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
PPTX
Evaluating Hype in scala
PPTX
Java script advance-auroskills (2)
PDF
Streams for (Co)Free!
PPTX
Programação reativa e o actor model
PPT
Groovy unleashed
Sharding and Load Balancing in Scala - Twitter's Finagle
Java 8: the good parts!
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
[QE 2018] Łukasz Gawron – Testing Batch and Streaming Spark Applications
Exploring Streams and Lambdas in Java8
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
Scala @ TechMeetup Edinburgh
Djangocon
An a z index of windows power shell commandss
Java8lambda
RIAs Done Right: Grails, Flex, and EXT GWT
The Steel industry, Elixir, PostgreSQL & file_fdw
Linked to ArrayList: the full story
Scale up your thinking
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Evaluating Hype in scala
Java script advance-auroskills (2)
Streams for (Co)Free!
Programação reativa e o actor model
Groovy unleashed
Ad

Viewers also liked (6)

PPT
Павел Кудинов: Сетевая многозадачность: событийные машины
PDF
Илья Щербак, Eltex
PDF
Mature optimization (Carlos Bueno, Facebook)
PDF
Дмитрий Дегтярев, "Хабикаса"
PPTX
Стриминг и эффективное чтение с DVD диска
PDF
Configuration Management Camp 2015
Павел Кудинов: Сетевая многозадачность: событийные машины
Илья Щербак, Eltex
Mature optimization (Carlos Bueno, Facebook)
Дмитрий Дегтярев, "Хабикаса"
Стриминг и эффективное чтение с DVD диска
Configuration Management Camp 2015
Ad

Similar to Julio Capote, Twitter (20)

PDF
Async Microservices with Twitter's Finagle
PPTX
Exploring Twitter's Finagle technology stack for microservices
PPTX
High Performance RPC with Finagle
PDF
Twitter Finagle
PDF
Scala.io
PPTX
Finagle Lightning Talk JPR 2014
PPTX
Introduction to Finch
PDF
Finagle - an intro to rpc & a sync programming in jvm
ODP
Finagle and Java Service Framework at Pinterest
PDF
Finch + Finagle OAuth2
PPTX
Finagle Your Own Codec - Scala By The Bay 2016
PPT
Distributed & Highly Available server applications in Java and Scala
PDF
Java one2013
PDF
ScalaDays Amsterdam - Don't block yourself
PDF
Finch.io - Purely Functional REST API with Finagle
PDF
From polling to real time: Scala, Akka, and Websockets from scratch
PDF
Functional Systems @ Twitter
PDF
Scala(finagle)@SmartNews_English
PDF
Lagom : Reactive microservice framework
PDF
Reasonable RPC with Remotely
Async Microservices with Twitter's Finagle
Exploring Twitter's Finagle technology stack for microservices
High Performance RPC with Finagle
Twitter Finagle
Scala.io
Finagle Lightning Talk JPR 2014
Introduction to Finch
Finagle - an intro to rpc & a sync programming in jvm
Finagle and Java Service Framework at Pinterest
Finch + Finagle OAuth2
Finagle Your Own Codec - Scala By The Bay 2016
Distributed & Highly Available server applications in Java and Scala
Java one2013
ScalaDays Amsterdam - Don't block yourself
Finch.io - Purely Functional REST API with Finagle
From polling to real time: Scala, Akka, and Websockets from scratch
Functional Systems @ Twitter
Scala(finagle)@SmartNews_English
Lagom : Reactive microservice framework
Reasonable RPC with Remotely

More from Ontico (20)

PDF
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
PDF
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
PPTX
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
PDF
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
PDF
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
PDF
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
PDF
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
PDF
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
PPTX
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
PPTX
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
PDF
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
PPTX
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
PPTX
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
PDF
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
PPT
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
PPTX
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
PPTX
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
PPTX
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
PPTX
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
PDF
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
KodekX | Application Modernization Development
PPT
Teaching material agriculture food technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
Dropbox Q2 2025 Financial Results & Investor Presentation
Mobile App Security Testing_ A Comprehensive Guide.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
KodekX | Application Modernization Development
Teaching material agriculture food technology
Chapter 3 Spatial Domain Image Processing.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The AUB Centre for AI in Media Proposal.docx
Digital-Transformation-Roadmap-for-Companies.pptx
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
Building Integrated photovoltaic BIPV_UPV.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
20250228 LYD VKU AI Blended-Learning.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation

Julio Capote, Twitter