SlideShare una empresa de Scribd logo
1 de 11
Sharding and Load Balancing in Scala
Twitter's Finagle
Geoff Ballinger
Technical Advisor at Mobile Acuity Ltd.
• some ML and Lisp in the early 90s
• C, C++ and Java since – embedded and server
• apps on BB, Android and iOS
• Mobile
• Startups
• Scaling
• Integration
• Deployment & Ops
>>> Background
>>> Finagle
https://blog.twitter.com/2011/finagl
e-protocol-agnostic-rpc-system
• Finagle is an extensible RPC system for Scala
• Protocol-agnostic and asynchronous
• Created, used and published by Twitter
• Built on netty and thus NIO
• Heavy use of Futures etc
• http://twitter.github.io/finagle/
• Multiple HTTP workers – part of the result
• Each shard is one or more identical workers
• Sharder scatters requests to the shards and
gathers the results
• Load balance between workers
• Fault tolerant
• Chance to play w/ Scala in anger!
• (Simple rational reconstruction)
>>> A simple sharder?
object Worker extends App {
try {
// Collect args
val port = Integer.parseInt(args(0))
val value = args(1)
// Define our service - just return the value provided!
val service = new Service[HttpRequest, HttpResponse] {
def apply(req: HttpRequest) = {
val buffer = ChannelBuffers.copiedBuffer(value, Charset.forName("UTF-8"))
val response = new DefaultHttpResponse(req.getProtocolVersion, HttpResponseStatus.OK)
response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain")
response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes())
response.setContent(buffer)
Future.value(response)
}
}
>>> Worker (1)
// Run this worker over the required port
val server = ServerBuilder()
.codec(Http())
.bindTo(new InetSocketAddress(port))
.name("Shard")
.build(service)
} catch {
case t: Throwable => {
System.err.println(t.getMessage())
System.err.println("Usage: Worker <port> <value>")
}
}
}
>>> Worker (2)
// Collect port arg
val port = Integer.parseInt(args(0))
// Build up shards from host specs on remaining command line
val shards = args.tail.map(spec => {
ClientBuilder()
.codec(Http())
.hosts(spec)
.hostConnectionLimit(10)
.retryPolicy(policy)
.build()
})
>>> Sharder (setup)
// Define our service - scatter to the shards and gather the results
val service = new Service[HttpRequest, HttpResponse] {
def apply(req: HttpRequest) = {
Future.collect(shards.map(shard => { // Scatter
shard(req).map(resp => resp.getContent().toString(CHARSET))
}))
.map(resps => { // Gather
val bf = ChannelBuffers.copiedBuffer(resps.reduceLeft(_+":"+_), CHARSET)
val resp = new DefaultHttpResponse(req.getProtocolVersion, HttpResponseStatus.OK)
resp.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain")
resp.setHeader(HttpHeaders.Names.CONTENT_LENGTH, bf.readableBytes())
resp.setContent(bf)
resp
})
}
}
>>> Sharder (service)
>>> Demo time!
>>> Reflections and Opinions
• Concise and expressive
• Shoulders of giants
• Poorly documented
• Exposes too many lower APIs
• Twitter vs Scala vs Akka Futures!
https://github.com/geoffballinger/simple-sharder
geoff@geoffballinger.co.uk
@geoffballinger
http://www.geoffballinger.co.uk
>>> Thanks for Listening!

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

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
 
Flamingo Training - Hello World
Flamingo Training - Hello WorldFlamingo Training - Hello World
Flamingo Training - Hello World
 
Flamingo Core Concepts
Flamingo Core ConceptsFlamingo Core Concepts
Flamingo Core Concepts
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Consul presentation
Consul presentationConsul presentation
Consul presentation
 
Algebird : Abstract Algebra for big data analytics. Devoxx 2014
Algebird : Abstract Algebra for big data analytics. Devoxx 2014Algebird : Abstract Algebra for big data analytics. Devoxx 2014
Algebird : Abstract Algebra for big data analytics. Devoxx 2014
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma Cloud
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
 
Kitura Todolist tutorial
Kitura Todolist tutorialKitura Todolist tutorial
Kitura Todolist tutorial
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Talk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetTalk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe Converset
 
Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams
 

Similar a Sharding and Load Balancing in Scala - Twitter's Finagle

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 

Similar a Sharding and Load Balancing in Scala - Twitter's Finagle (20)

Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Finagle - an intro to rpc & a sync programming in jvm
Finagle - an intro to rpc & a sync programming in jvmFinagle - an intro to rpc & a sync programming in jvm
Finagle - an intro to rpc & a sync programming in jvm
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Nordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API DocumentationNordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API Documentation
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 

Más de Geoff Ballinger

Más de Geoff Ballinger (17)

Highly Accurate Alignment of Data from Measurement Trains:

 the Challenges o...
Highly Accurate Alignment of Data from Measurement Trains:

 the Challenges o...Highly Accurate Alignment of Data from Measurement Trains:

 the Challenges o...
Highly Accurate Alignment of Data from Measurement Trains:

 the Challenges o...
 
The Internet Of (very big) Things
The Internet Of (very big) ThingsThe Internet Of (very big) Things
The Internet Of (very big) Things
 
Docker in Embedded Systems
Docker in Embedded SystemsDocker in Embedded Systems
Docker in Embedded Systems
 
The Load Balancer: War Stories with HAProxy
The Load Balancer: War Stories with HAProxyThe Load Balancer: War Stories with HAProxy
The Load Balancer: War Stories with HAProxy
 
The Power of Conversation
The Power of ConversationThe Power of Conversation
The Power of Conversation
 
Mobile in 2016?
Mobile in 2016?Mobile in 2016?
Mobile in 2016?
 
The Buzz from Barcelona: MWC16
The Buzz from Barcelona: MWC16The Buzz from Barcelona: MWC16
The Buzz from Barcelona: MWC16
 
MoMoGPW: IoT's turn for the Kool-Aid?
MoMoGPW: IoT's turn for the Kool-Aid?MoMoGPW: IoT's turn for the Kool-Aid?
MoMoGPW: IoT's turn for the Kool-Aid?
 
The “other side” of MWC: IoT’s turn for the Kool-Aid?
The “other side” of MWC: IoT’s turn for the Kool-Aid?The “other side” of MWC: IoT’s turn for the Kool-Aid?
The “other side” of MWC: IoT’s turn for the Kool-Aid?
 
MVP: Minimum Viable apP?
MVP: Minimum Viable apP?MVP: Minimum Viable apP?
MVP: Minimum Viable apP?
 
Mobile as an Entrepreneurial Opportunity
Mobile as an Entrepreneurial OpportunityMobile as an Entrepreneurial Opportunity
Mobile as an Entrepreneurial Opportunity
 
Mobile Platforms Redux
Mobile Platforms ReduxMobile Platforms Redux
Mobile Platforms Redux
 
Connecting the real world with your mobile - or how to ask "What's that?"
Connecting the real world with your mobile - or how to ask "What's that?"Connecting the real world with your mobile - or how to ask "What's that?"
Connecting the real world with your mobile - or how to ask "What's that?"
 
Barcamp Glasgow 2010 - Mobile
Barcamp Glasgow 2010 - MobileBarcamp Glasgow 2010 - Mobile
Barcamp Glasgow 2010 - Mobile
 
MWC2010 Overview
MWC2010 OverviewMWC2010 Overview
MWC2010 Overview
 
Visual Interactivity
Visual InteractivityVisual Interactivity
Visual Interactivity
 
BarCampScotland: What Is Visual Interactivity?
BarCampScotland: What Is Visual Interactivity?BarCampScotland: What Is Visual Interactivity?
BarCampScotland: What Is Visual Interactivity?
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Sharding and Load Balancing in Scala - Twitter's Finagle

  • 1. Sharding and Load Balancing in Scala Twitter's Finagle Geoff Ballinger Technical Advisor at Mobile Acuity Ltd.
  • 2. • some ML and Lisp in the early 90s • C, C++ and Java since – embedded and server • apps on BB, Android and iOS • Mobile • Startups • Scaling • Integration • Deployment & Ops >>> Background
  • 3. >>> Finagle https://blog.twitter.com/2011/finagl e-protocol-agnostic-rpc-system • Finagle is an extensible RPC system for Scala • Protocol-agnostic and asynchronous • Created, used and published by Twitter • Built on netty and thus NIO • Heavy use of Futures etc • http://twitter.github.io/finagle/
  • 4. • Multiple HTTP workers – part of the result • Each shard is one or more identical workers • Sharder scatters requests to the shards and gathers the results • Load balance between workers • Fault tolerant • Chance to play w/ Scala in anger! • (Simple rational reconstruction) >>> A simple sharder?
  • 5. object Worker extends App { try { // Collect args val port = Integer.parseInt(args(0)) val value = args(1) // Define our service - just return the value provided! val service = new Service[HttpRequest, HttpResponse] { def apply(req: HttpRequest) = { val buffer = ChannelBuffers.copiedBuffer(value, Charset.forName("UTF-8")) val response = new DefaultHttpResponse(req.getProtocolVersion, HttpResponseStatus.OK) response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain") response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes()) response.setContent(buffer) Future.value(response) } } >>> Worker (1)
  • 6. // Run this worker over the required port val server = ServerBuilder() .codec(Http()) .bindTo(new InetSocketAddress(port)) .name("Shard") .build(service) } catch { case t: Throwable => { System.err.println(t.getMessage()) System.err.println("Usage: Worker <port> <value>") } } } >>> Worker (2)
  • 7. // Collect port arg val port = Integer.parseInt(args(0)) // Build up shards from host specs on remaining command line val shards = args.tail.map(spec => { ClientBuilder() .codec(Http()) .hosts(spec) .hostConnectionLimit(10) .retryPolicy(policy) .build() }) >>> Sharder (setup)
  • 8. // Define our service - scatter to the shards and gather the results val service = new Service[HttpRequest, HttpResponse] { def apply(req: HttpRequest) = { Future.collect(shards.map(shard => { // Scatter shard(req).map(resp => resp.getContent().toString(CHARSET)) })) .map(resps => { // Gather val bf = ChannelBuffers.copiedBuffer(resps.reduceLeft(_+":"+_), CHARSET) val resp = new DefaultHttpResponse(req.getProtocolVersion, HttpResponseStatus.OK) resp.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain") resp.setHeader(HttpHeaders.Names.CONTENT_LENGTH, bf.readableBytes()) resp.setContent(bf) resp }) } } >>> Sharder (service)
  • 10. >>> Reflections and Opinions • Concise and expressive • Shoulders of giants • Poorly documented • Exposes too many lower APIs • Twitter vs Scala vs Akka Futures!