SlideShare a Scribd company logo
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!

More Related Content

PDF
Finch.io - Purely Functional REST API with Finagle
PPTX
High Performance RPC with Finagle
PDF
Introduction to Asynchronous scala
PDF
Graphql with Flamingo
PDF
Introduction to reactive programming & ReactiveCocoa
PDF
Swift Sequences & Collections
PDF
React native-firebase startup-mtup
 
PDF
Annotation processing and code gen
Finch.io - Purely Functional REST API with Finagle
High Performance RPC with Finagle
Introduction to Asynchronous scala
Graphql with Flamingo
Introduction to reactive programming & ReactiveCocoa
Swift Sequences & Collections
React native-firebase startup-mtup
 
Annotation processing and code gen

What's hot (20)

PPTX
Exploring Twitter's Finagle technology stack for microservices
PDF
Flamingo Training - Hello World
PDF
Flamingo Core Concepts
PDF
Rntb20200805
 
PDF
Callbacks and control flow in Node js
PDF
JavaOne 2013: Java 8 - The Good Parts
PDF
Javascript Promises/Q Library
PDF
Node Boot Camp
PPTX
Avoiding Callback Hell with Async.js
PDF
Consul presentation
PPTX
Algebird : Abstract Algebra for big data analytics. Devoxx 2014
PDF
Nestjs MasterClass Slides
PDF
Managing GraphQL servers with AWS Fargate & Prisma Cloud
PDF
End to end todo list app with NestJs - Angular - Redux & Redux Saga
PDF
Kitura Todolist tutorial
PDF
RxSwift to Combine
PDF
RxSwift to Combine
PDF
AWS Java SDK @ scale
PDF
Talk KVO with rac by Philippe Converset
PPTX
Connect S3 with Kafka using Akka Streams
Exploring Twitter's Finagle technology stack for microservices
Flamingo Training - Hello World
Flamingo Core Concepts
Rntb20200805
 
Callbacks and control flow in Node js
JavaOne 2013: Java 8 - The Good Parts
Javascript Promises/Q Library
Node Boot Camp
Avoiding Callback Hell with Async.js
Consul presentation
Algebird : Abstract Algebra for big data analytics. Devoxx 2014
Nestjs MasterClass Slides
Managing GraphQL servers with AWS Fargate & Prisma Cloud
End to end todo list app with NestJs - Angular - Redux & Redux Saga
Kitura Todolist tutorial
RxSwift to Combine
RxSwift to Combine
AWS Java SDK @ scale
Talk KVO with rac by Philippe Converset
Connect S3 with Kafka using Akka Streams
Ad

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

PDF
Finagle - an intro to rpc & a sync programming in jvm
PDF
Julio Capote, Twitter
PDF
Scala.io
PDF
Twitter Finagle
PDF
Reasonable RPC with Remotely
PDF
Java one2013
PPTX
Finagle Your Own Codec - Scala By The Bay 2016
PPTX
Tools for Making Machine Learning more Reactive
PPT
Distributed & Highly Available server applications in Java and Scala
PDF
Async Microservices with Twitter's Finagle
PDF
Lessons from Sharding Solr
PDF
Lessons From Sharding Solr At Etsy: Presented by Gregg Donovan, Etsy
PPTX
Introduction to Finch
PDF
Sane Sharding with Akka Cluster
KEY
Building Distributed Systems in Scala
PDF
Finagle By Twitter Engineer @ Knoldus
PDF
JDD2015: Sharding with Akka Cluster: From Theory to Production - Krzysztof Ot...
PDF
Asynchronous web apps with the Play Framework 2.0
ODP
Finagle and Java Service Framework at Pinterest
PDF
Sane Sharding with Akka Cluster
Finagle - an intro to rpc & a sync programming in jvm
Julio Capote, Twitter
Scala.io
Twitter Finagle
Reasonable RPC with Remotely
Java one2013
Finagle Your Own Codec - Scala By The Bay 2016
Tools for Making Machine Learning more Reactive
Distributed & Highly Available server applications in Java and Scala
Async Microservices with Twitter's Finagle
Lessons from Sharding Solr
Lessons From Sharding Solr At Etsy: Presented by Gregg Donovan, Etsy
Introduction to Finch
Sane Sharding with Akka Cluster
Building Distributed Systems in Scala
Finagle By Twitter Engineer @ Knoldus
JDD2015: Sharding with Akka Cluster: From Theory to Production - Krzysztof Ot...
Asynchronous web apps with the Play Framework 2.0
Finagle and Java Service Framework at Pinterest
Sane Sharding with Akka Cluster
Ad

More from Geoff Ballinger (17)

PPTX
Highly Accurate Alignment of Data from Measurement Trains:

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

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

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PDF
Encapsulation theory and applications.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Cloud computing and distributed systems.
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Modernizing your data center with Dell and AMD
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Spectral efficient network and resource selection model in 5G networks
Mobile App Security Testing_ A Comprehensive Guide.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Encapsulation theory and applications.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Review of recent advances in non-invasive hemoglobin estimation
Dropbox Q2 2025 Financial Results & Investor Presentation
Cloud computing and distributed systems.
NewMind AI Weekly Chronicles - August'25 Week I
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
Modernizing your data center with Dell and AMD
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Unlocking AI with Model Context Protocol (MCP)
Digital-Transformation-Roadmap-for-Companies.pptx
Understanding_Digital_Forensics_Presentation.pptx
Approach and Philosophy of On baking technology
Spectral efficient network and resource selection model in 5G networks

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!