SlideShare a Scribd company logo
1 of 63
Exploring Twitter’s
Finagle technology stack
for microservices
Tomasz Kogut / @almendar
XII Tricity Scala User Group Meetup
About me:
• Software Engineer at
• Working in the internet advertisement
industry
• I try to create distributed, highly performant
systems that will run on the JVM
• Programming in Scala since ~2011
Microservices
questionnaire
Who uses μ-services approach?
Who has a system that would like to break down into smaller pieces?
What we already know?
• Working on huge monolithic projects is hard
• Complexity and interdependencies become
incomprehensible at some point
• We all fell in our guts that breaking it down
is a way to go
• Single responsibility principle but for
services
The plan
1. Create multiple git repositories
2. Create/copy/move code around repos
3. Pour it all with a fair share of
REST/HTTP
4. Extract common code/models into libs
5. Run it!
Let’s go to production!
So what
happened?
Paying for the lunch
• Easy to develop
• Hard to operate
• More fine-grained services boost both
traits
Things to address
• A lot of stuff from “Fallacies of distributed computing"
• Tracing request across different services
• Service discovery and tracing service topology
• Message serialization
• Distributing load across nodes
• Measuring performance and finding bottlenecks is not easy
• Interface contracts can introduce hidden coupling
• Duplication of effort
• Historically we were a .Net shop
• Think spring-like approach
• Moved to API first approach (although we were
running some kind of μ-service approach to some
extend)
• Splitting one of the business features into small-
chunks using whatever tech stack we want so we
went akka/akka-http
• We didn’t want to use akka clustering
• Recreating utils e.g. request retry
• Establishing new project = work upfront before creating
any business value e.g. metrics
• Every project had it’s own structure - mental context
switching
• REST is good but other protocols might be better
• Fighting the “spray DSL” and marshallers 😀
• Creating json is annoying and automatic derivation from
classes was useless most of the time
• We had to think how to properly version our apis and hold
backward compatibility
• We had situations where multiple services needed to be
deployed for the solution to work (hidden monolith)
• How do I run this service locally?
What is it?
• Protocol agnostic RPC system for JVM
• Based on Netty
• Allows for building servers and clients
• Core platform on which Twitter is build
• "Your Server as a Function" by Marius
Eriksen
Foundations
• Futures
• Services
• Filters
Future
• NOT the Scala one unfortunately but very close
• Some api differences
- import com.twitter.util.Future
- Future.value == Future.successful
- Future.exception == Future.failed
- Future.collect == Future.sequence
• Usual monadic composition with flatMap and map
• There is also twitter’s Try, Duration and a bunch of others…
Service
• Basic building block in Finagle
• Just a function that returns a Future
• Servers implement services to which Finagle dispatches incoming requests
• Finagle furnishes clients with instances of Service representing either virtual or
concrete remote servers
abstract class Service[-Req, +Rep] extends (Req =>
Future[Rep])
Example local service (1)
import com.twitter.finagle.Service
import com.twitter.util.Future
val lengthService = Service.mk[String, Int] { req =>
Future.value(req.length)
}
lengthService("Hello TSUG").foreach(println)
import com.twitter.finagle.http
import com.twitter.finagle.Service
import com.twitter.util.Future
import com.twitter.finagle.Http
val service = new Service[http.Request, http.Response] {
def apply(req: http.Request): Future[http.Response] =
Future.value(
http.Response(req.version, http.Status.Ok)
)
}
val server = Http.serve(":8080", service)
Example http server (2)
import com.twitter.finagle.http.Method.Get
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.service.FailFastFactory.FailFast
import com.twitter.util.Future
val productServiceHttpClient: Service[Request, Response] =
Http.client.configured(FailFast(false)).newClient("127.0.0.1:8080",
"productService").toService
val response: Future[Response] =
productServiceHttpClient(Request(Get,"/products/22"))
response.foreach{ response =>
println(response.statusCode)
println(response.contentString)
}
Example http client (3)
Other protocols client
examples
var memCache = ClientBuilder()
.name("mc")
.codec(Memcached())
.hostConnectionLimit(config.concurrency())
.hosts(config.hosts())
val mySqlClient = Mysql.client
.withCredentials(username(), password())
.withDatabase(dbname())
.newRichClient("%s:%d".format(host().getHostName, host().getPort))
Services represents
clients and servers
symmetrically
Please notice that:
Filter
• Again a function that returns a Future
• Filters are always attached to Services altering their
behavior
• Used for application agnostic concerns such as: timeouts,
retry policies, service statistics, and authentication
abstract class Filter[-ReqIn, +RepOut, +ReqOut, -RepIn]
extends ((ReqIn, Service[ReqOut, RepIn]) => Future[RepOut])
Filter
• Filters just like any other functions
compose
• There is a andThen method that chains
different filters with each other and in the
end with service
Local service filter
import com.twitter.finagle.{Filter, Service}
import com.twitter.util.Future
val someStringMetrics = Service.mk[String,Int] { req =>
Future.value(req.length)
}
val evenMetricsFilter = new Filter[Float, Boolean, String, Int] {
override def apply(input: Float,
stringMetricsService: Service[String, Int]): Future[Boolean] = {
stringMetricsService(input.toString).map(_ % 2 == 0)
}
}
(evenMetricsFilter andThen someStringMetrics)(1.234f)
import com.twitter.finagle.{Http,Service, Filter}
import com.twitter.finagle.http.{Request,Response}
import com.twitter.finagle.service.TimeoutFilter
import com.twitter.util.MockTimer
import com.twitter.conversions.time._
val httpClient: Service[Request, Response] =
Http.client.newService("twitter.com")
val timeoutFilter: Filter[Request, Response, Request, Response] =
new TimeoutFilter[Request, Response](30.seconds, new MockTimer)
val httpClientWithTimeout: Service[Request, Response] =
timeoutFilter andThen httpClient
Filter example http client
WARNING
This is only a showcase, timeouts for http clients are best configured by Http.client object
How to implement
this?
Stacking filters
recordHandletime andThen
traceRequest andThen
collectJvmStats andThen
parseRequest andThen
logRequest andThen
recordClientStats andThen
sanitize andThen
respondToHealthCheck andThen
applyTrafficControl andThen
virtualHostServer
Fronted webservers configuration at twitter:
Cool client filters
(or wannabe-filters)
• MonitorFilter - handling exceptions
• StatsFilter - exposing metrics
• RetryFilter - retying calls with configured budget and a back-off policy
• TimeoutFilter - mentioned earlier, for different aspects like idle time, request
time, connection time ect.
• LoadBalancing (not really a filter) - distributed load across nodes, just pass
multiple host values
• FailFast (not really a filter) - mark node as dead for a certain period of time
• Unfortunately not all functionality can be
expressed with Filters
• Some things are a bit hairy - e.g. request
cancelation
• Beneath implementations is non-trivial but
comprehensible
• But the good part is that it all works out to the
box for free with almost none configuration!
There is more in Finagle to
explore:
• Thrift protocol
• Mux - multiplexing RPC
• ZooKeeper support
• Network location naming
Twitter
Server
Even more goodies
Twitter Server
• A “template” for finagle-based server
• Flags
• Logging
• Metrics
• Admin interface
Flags (1)
• Cmd line arguments passed to the
application
• A remedy to “How do I start this thing
and what are the options?”
• Smart with type inference and parsing
capabilities
Flags (2)
val addr = flag("bind", new InetSocketAddress(0), "Bind address")
val durations = flag("alarms", (1.second, 5.second), "2 alarm durations")
$ java -jar target/myserver-1.0.0-SNAPSHOT.jar -help
AdvancedServer
-alarm_durations='1.seconds,5.seconds': 2 alarm durations
-help='false': Show this help
-admin.port=':9990': Admin http server port
-bind=':0': Network interface to use
-log.level='INFO': Log level
-log.output='/dev/stderr': Output file
-what='hello': String to return
Option for fail fast when missing a flag
Logging
• Twitter server provides a logging trait
• It can be configured with standard flags
• Can be tuned on-the-fly
Admin interface loggers
control
Metrics
• Defining own statistics
• JVM stats
• Processing and network stats
Others
• Linting your server for problems
• Looking at threads
• Profiling
Admin interface
Finatra
What is it?
• Finatra is build atop Finagle and Twitter
Server
• Finatra does all the heavy-lifting that one
needs to do when working only with
Finagle
Finatra features
• Dependency injection using Guice
• JSON handling with Jackson
• Mustache support
• Routing
• Integrates it all together nicely
package pl.tk.finagle.recommendation.controller
import javax.inject.{Inject, Singleton}
import com.twitter.finagle.http.Request
import com.twitter.finagle.tracing.ClientTracingFilter.TracingFilter
import com.twitter.finatra.http.Controller
import com.twitter.finatra.request._
import com.twitter.inject.Logging
import pl.tk.finagle.recommendation.engine.{RecommendationCmd, RecommendationEngine}
case class RecommendationFromCookieRequest(@Inject request: Request,
@RouteParam cookieId: Int,
@RouteParam eshopId: Int,
@Header `x-auth`: String)
@Singleton
class RecommendationController @Inject()
(recommendationEngine: RecommendationEngine)
extends Controller with Logging {
get("/recommend/:eshop_id/:cookie_id") { r: RecommendationFromCookieRequest =>
infoResult("Hello") {
TracingFilter("RecommendationEngine") andThen
recommendationEngine apply
RecommendationCmd(r.cookieId, r.eshopId)
}
}
}
Unified error reporting
➜ finagle-spike git:(master) ✗ curl -v 127.0.0.1:2001/recommend/32/wsf
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 2001 (#0)
> GET /recommend/32/wsf HTTP/1.1
> Host: 127.0.0.1:2001
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< Content-Type: application/json; charset=utf-8
< Server: Finatra
< Date: Wed, 30 Mar 2016 07:05:53 +00:00
< Content-Length: 79
<
* Connection #0 to host 127.0.0.1 left intact
{"errors":["cookie_id: 'wsf' is not a valid int","x-auth: header is required"]}%
JSON Support
• Build on jackson-module-scala
• Support for case classes (de)serlialization
• Integrated with Joda
• Error accumulation (instead of fail-fast)
• Integration with routing
• Most of the cases just return object
Customizing Json
class Server extends HttpServer {
override def jacksonModule = CustomJacksonModule
...
}
object CustomJacksonModule extends FinatraJacksonModule {
override val additionalJacksonModules = Seq(
new SimpleModule {
addSerializer(LocalDateParser)
})
override val serializationInclusion = Include.NON_EMPTY
override val propertyNamingStrategy = CamelCasePropertyNamingStrategy
override def additionalMapperConfiguration(mapper: ObjectMapper) {
mapper.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true)
}
}
Validation
import com.twitter.finatra.validation._
import org.joda.time.DateTime
case class GroupRequest(@NotEmpty name: String,
description: Option[String],
tweetIds: Set[Long],
dates: Dates) {
@MethodValidation
def validateName = {
ValidationResult.validate(
name.startsWith("grp-"),
"name must start with 'grp-'")
}
}
case class Dates(@PastTime start: DateTime,
@PastTime end: DateTime)
Also checked at routing time
Testing (1)
• Based on ScalaTest
• Feature testing (both black box and white box)
- looking at external interface of our service
• Integration tests - only a subset of modules is
instantiated and tested
• Finatra does not provide anything for unit
testing
Testing (2)
• Smart JSON diff
• Integration with DI
• Easy mocking
• Embedded http server with our service
last but not
least…
What is it?
• Distributed request tracing
• Based on Google Dapper paper
• Helps getting insight on how the services
interact
Zipkin
Python pyramid_zipkin
Pyramid Http
(B3)
Http (B3) Kafka | Scribe Yes
py2, py3
support.
Java brave
Jersey,
RestEASY,
JAXRS2,
Apache
HttpClient,
Mysql
Http (B3)
Http, Kafka,
Scribe
Yes
Java 6 or
higher
Scala finagle-zipkin Finagle
Http (B3),
Thrift
Scribe Yes
Ruby zipkin-tracer Rack Http (B3)
Http, Kafka,
Scribe
Yes
lc support.
Ruby 2.0 or
higher
C#
ZipkinTracerM OWIN,
Http (B3) Http Yes
lc support.
Not tied to finagle
Zipkin Architecture
DEMO APP
Recommendation
ProductsService
UserProfile
1 GetProducts
2 GetPromotedProducts
GetUser
CookieId, Eshop
Thank you!

More Related Content

What's hot

OpenTelemetry Introduction
OpenTelemetry Introduction OpenTelemetry Introduction
OpenTelemetry Introduction DimitrisFinas1
 
Scaling Data and ML with Apache Spark and Feast
Scaling Data and ML with Apache Spark and FeastScaling Data and ML with Apache Spark and Feast
Scaling Data and ML with Apache Spark and FeastDatabricks
 
Kubernetes Deployment Strategies
Kubernetes Deployment StrategiesKubernetes Deployment Strategies
Kubernetes Deployment StrategiesAbdennour TM
 
Designing a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd productsDesigning a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd productsJulian Mazzitelli
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesAraf Karsh Hamid
 
An Intrudction to OpenStack 2017
An Intrudction to OpenStack 2017An Intrudction to OpenStack 2017
An Intrudction to OpenStack 2017Haim Ateya
 
FIWARE Global Summit - FogFlow, a new GE for IoT Edge Computing
FIWARE Global Summit - FogFlow, a new GE for IoT Edge ComputingFIWARE Global Summit - FogFlow, a new GE for IoT Edge Computing
FIWARE Global Summit - FogFlow, a new GE for IoT Edge ComputingFIWARE
 
Everything You wanted to Know About Distributed Tracing
Everything You wanted to Know About Distributed TracingEverything You wanted to Know About Distributed Tracing
Everything You wanted to Know About Distributed TracingAmuhinda Hungai
 
Distributed Tracing with Jaeger
Distributed Tracing with JaegerDistributed Tracing with Jaeger
Distributed Tracing with JaegerInho Kang
 
Introduction to Distributed Tracing
Introduction to Distributed TracingIntroduction to Distributed Tracing
Introduction to Distributed Tracingpetabridge
 
Introduction of Kubernetes - Trang Nguyen
Introduction of Kubernetes - Trang NguyenIntroduction of Kubernetes - Trang Nguyen
Introduction of Kubernetes - Trang NguyenTrang Nguyen
 
Service Mesh on Kubernetes with Istio
Service Mesh on Kubernetes with IstioService Mesh on Kubernetes with Istio
Service Mesh on Kubernetes with IstioMichelle Holley
 
Adopting OpenTelemetry
Adopting OpenTelemetryAdopting OpenTelemetry
Adopting OpenTelemetryVincent Behar
 
OpenTelemetry For Developers
OpenTelemetry For DevelopersOpenTelemetry For Developers
OpenTelemetry For DevelopersKevin Brockhoff
 
KCD-OpenTelemetry.pdf
KCD-OpenTelemetry.pdfKCD-OpenTelemetry.pdf
KCD-OpenTelemetry.pdfRui Liu
 
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...LibbySchulze
 
Circuit Breaker Pattern
Circuit Breaker PatternCircuit Breaker Pattern
Circuit Breaker PatternTung Nguyen
 

What's hot (20)

OpenTelemetry Introduction
OpenTelemetry Introduction OpenTelemetry Introduction
OpenTelemetry Introduction
 
Scaling Data and ML with Apache Spark and Feast
Scaling Data and ML with Apache Spark and FeastScaling Data and ML with Apache Spark and Feast
Scaling Data and ML with Apache Spark and Feast
 
Kubernetes Deployment Strategies
Kubernetes Deployment StrategiesKubernetes Deployment Strategies
Kubernetes Deployment Strategies
 
Designing a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd productsDesigning a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd products
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing Strategies
 
An Intrudction to OpenStack 2017
An Intrudction to OpenStack 2017An Intrudction to OpenStack 2017
An Intrudction to OpenStack 2017
 
FIWARE Global Summit - FogFlow, a new GE for IoT Edge Computing
FIWARE Global Summit - FogFlow, a new GE for IoT Edge ComputingFIWARE Global Summit - FogFlow, a new GE for IoT Edge Computing
FIWARE Global Summit - FogFlow, a new GE for IoT Edge Computing
 
Everything You wanted to Know About Distributed Tracing
Everything You wanted to Know About Distributed TracingEverything You wanted to Know About Distributed Tracing
Everything You wanted to Know About Distributed Tracing
 
Distributed Tracing with Jaeger
Distributed Tracing with JaegerDistributed Tracing with Jaeger
Distributed Tracing with Jaeger
 
Introduction to Distributed Tracing
Introduction to Distributed TracingIntroduction to Distributed Tracing
Introduction to Distributed Tracing
 
Introduction of Kubernetes - Trang Nguyen
Introduction of Kubernetes - Trang NguyenIntroduction of Kubernetes - Trang Nguyen
Introduction of Kubernetes - Trang Nguyen
 
Dynamic Routing RIP
Dynamic Routing RIPDynamic Routing RIP
Dynamic Routing RIP
 
Service Mesh on Kubernetes with Istio
Service Mesh on Kubernetes with IstioService Mesh on Kubernetes with Istio
Service Mesh on Kubernetes with Istio
 
Adopting OpenTelemetry
Adopting OpenTelemetryAdopting OpenTelemetry
Adopting OpenTelemetry
 
Gitlab, GitOps & ArgoCD
Gitlab, GitOps & ArgoCDGitlab, GitOps & ArgoCD
Gitlab, GitOps & ArgoCD
 
OpenTelemetry For Developers
OpenTelemetry For DevelopersOpenTelemetry For Developers
OpenTelemetry For Developers
 
KCD-OpenTelemetry.pdf
KCD-OpenTelemetry.pdfKCD-OpenTelemetry.pdf
KCD-OpenTelemetry.pdf
 
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...Understand your system like never before with OpenTelemetry, Grafana, and Pro...
Understand your system like never before with OpenTelemetry, Grafana, and Pro...
 
SRE & Kubernetes
SRE & KubernetesSRE & Kubernetes
SRE & Kubernetes
 
Circuit Breaker Pattern
Circuit Breaker PatternCircuit Breaker Pattern
Circuit Breaker Pattern
 

Similar to Exploring Twitter's Finagle technology stack for microservices

Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesMahmoudZidan41
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20....Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...Javier García Magna
 
170215 msa intro
170215 msa intro170215 msa intro
170215 msa introSonic leigh
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudyJohn Adams
 
Develop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverlessDevelop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverlessLalit Kale
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Derek Ashmore
 
Iot cloud service v2.0
Iot cloud service v2.0Iot cloud service v2.0
Iot cloud service v2.0Vinod Wilson
 
Stay productive_while_slicing_up_the_monolith
Stay productive_while_slicing_up_the_monolithStay productive_while_slicing_up_the_monolith
Stay productive_while_slicing_up_the_monolithMarkus Eisele
 
Planning to Fail #phpuk13
Planning to Fail #phpuk13Planning to Fail #phpuk13
Planning to Fail #phpuk13Dave Gardner
 
Exploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeExploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeAlex Thissen
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC vipin kumar
 
Microservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsMicroservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsŁukasz Sowa
 
Micro Services Architecture
Micro Services ArchitectureMicro Services Architecture
Micro Services ArchitectureRanjan Baisak
 
A microservices journey - Round 2
A microservices journey - Round 2A microservices journey - Round 2
A microservices journey - Round 2Christian Posta
 
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018Amazon Web Services Korea
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101Huy Vo
 
Concurrency at Scale: Evolution to Micro-Services
Concurrency at Scale:  Evolution to Micro-ServicesConcurrency at Scale:  Evolution to Micro-Services
Concurrency at Scale: Evolution to Micro-ServicesRandy Shoup
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...smallerror
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...xlight
 
Fixing twitter
Fixing twitterFixing twitter
Fixing twitterRoger Xia
 

Similar to Exploring Twitter's Finagle technology stack for microservices (20)

Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20....Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
 
170215 msa intro
170215 msa intro170215 msa intro
170215 msa intro
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudy
 
Develop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverlessDevelop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverless
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15
 
Iot cloud service v2.0
Iot cloud service v2.0Iot cloud service v2.0
Iot cloud service v2.0
 
Stay productive_while_slicing_up_the_monolith
Stay productive_while_slicing_up_the_monolithStay productive_while_slicing_up_the_monolith
Stay productive_while_slicing_up_the_monolith
 
Planning to Fail #phpuk13
Planning to Fail #phpuk13Planning to Fail #phpuk13
Planning to Fail #phpuk13
 
Exploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeExploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscape
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC
 
Microservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsMicroservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problems
 
Micro Services Architecture
Micro Services ArchitectureMicro Services Architecture
Micro Services Architecture
 
A microservices journey - Round 2
A microservices journey - Round 2A microservices journey - Round 2
A microservices journey - Round 2
 
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101
 
Concurrency at Scale: Evolution to Micro-Services
Concurrency at Scale:  Evolution to Micro-ServicesConcurrency at Scale:  Evolution to Micro-Services
Concurrency at Scale: Evolution to Micro-Services
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 

Recently uploaded

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

Exploring Twitter's Finagle technology stack for microservices

  • 1. Exploring Twitter’s Finagle technology stack for microservices Tomasz Kogut / @almendar XII Tricity Scala User Group Meetup
  • 2. About me: • Software Engineer at • Working in the internet advertisement industry • I try to create distributed, highly performant systems that will run on the JVM • Programming in Scala since ~2011
  • 4. questionnaire Who uses μ-services approach? Who has a system that would like to break down into smaller pieces?
  • 5. What we already know? • Working on huge monolithic projects is hard • Complexity and interdependencies become incomprehensible at some point • We all fell in our guts that breaking it down is a way to go • Single responsibility principle but for services
  • 6. The plan 1. Create multiple git repositories 2. Create/copy/move code around repos 3. Pour it all with a fair share of REST/HTTP 4. Extract common code/models into libs 5. Run it!
  • 7. Let’s go to production!
  • 8.
  • 9.
  • 11.
  • 12. Paying for the lunch • Easy to develop • Hard to operate • More fine-grained services boost both traits
  • 13. Things to address • A lot of stuff from “Fallacies of distributed computing" • Tracing request across different services • Service discovery and tracing service topology • Message serialization • Distributing load across nodes • Measuring performance and finding bottlenecks is not easy • Interface contracts can introduce hidden coupling • Duplication of effort
  • 14.
  • 15. • Historically we were a .Net shop • Think spring-like approach • Moved to API first approach (although we were running some kind of μ-service approach to some extend) • Splitting one of the business features into small- chunks using whatever tech stack we want so we went akka/akka-http
  • 16. • We didn’t want to use akka clustering • Recreating utils e.g. request retry • Establishing new project = work upfront before creating any business value e.g. metrics • Every project had it’s own structure - mental context switching • REST is good but other protocols might be better • Fighting the “spray DSL” and marshallers 😀
  • 17. • Creating json is annoying and automatic derivation from classes was useless most of the time • We had to think how to properly version our apis and hold backward compatibility • We had situations where multiple services needed to be deployed for the solution to work (hidden monolith) • How do I run this service locally?
  • 18.
  • 19. What is it? • Protocol agnostic RPC system for JVM • Based on Netty • Allows for building servers and clients • Core platform on which Twitter is build • "Your Server as a Function" by Marius Eriksen
  • 21. Future • NOT the Scala one unfortunately but very close • Some api differences - import com.twitter.util.Future - Future.value == Future.successful - Future.exception == Future.failed - Future.collect == Future.sequence • Usual monadic composition with flatMap and map • There is also twitter’s Try, Duration and a bunch of others…
  • 22. Service • Basic building block in Finagle • Just a function that returns a Future • Servers implement services to which Finagle dispatches incoming requests • Finagle furnishes clients with instances of Service representing either virtual or concrete remote servers abstract class Service[-Req, +Rep] extends (Req => Future[Rep])
  • 23. Example local service (1) import com.twitter.finagle.Service import com.twitter.util.Future val lengthService = Service.mk[String, Int] { req => Future.value(req.length) } lengthService("Hello TSUG").foreach(println)
  • 24. import com.twitter.finagle.http import com.twitter.finagle.Service import com.twitter.util.Future import com.twitter.finagle.Http val service = new Service[http.Request, http.Response] { def apply(req: http.Request): Future[http.Response] = Future.value( http.Response(req.version, http.Status.Ok) ) } val server = Http.serve(":8080", service) Example http server (2)
  • 25. import com.twitter.finagle.http.Method.Get import com.twitter.finagle.{Http, Service} import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.service.FailFastFactory.FailFast import com.twitter.util.Future val productServiceHttpClient: Service[Request, Response] = Http.client.configured(FailFast(false)).newClient("127.0.0.1:8080", "productService").toService val response: Future[Response] = productServiceHttpClient(Request(Get,"/products/22")) response.foreach{ response => println(response.statusCode) println(response.contentString) } Example http client (3)
  • 26. Other protocols client examples var memCache = ClientBuilder() .name("mc") .codec(Memcached()) .hostConnectionLimit(config.concurrency()) .hosts(config.hosts()) val mySqlClient = Mysql.client .withCredentials(username(), password()) .withDatabase(dbname()) .newRichClient("%s:%d".format(host().getHostName, host().getPort))
  • 27. Services represents clients and servers symmetrically Please notice that:
  • 28. Filter • Again a function that returns a Future • Filters are always attached to Services altering their behavior • Used for application agnostic concerns such as: timeouts, retry policies, service statistics, and authentication abstract class Filter[-ReqIn, +RepOut, +ReqOut, -RepIn] extends ((ReqIn, Service[ReqOut, RepIn]) => Future[RepOut])
  • 29. Filter • Filters just like any other functions compose • There is a andThen method that chains different filters with each other and in the end with service
  • 30. Local service filter import com.twitter.finagle.{Filter, Service} import com.twitter.util.Future val someStringMetrics = Service.mk[String,Int] { req => Future.value(req.length) } val evenMetricsFilter = new Filter[Float, Boolean, String, Int] { override def apply(input: Float, stringMetricsService: Service[String, Int]): Future[Boolean] = { stringMetricsService(input.toString).map(_ % 2 == 0) } } (evenMetricsFilter andThen someStringMetrics)(1.234f)
  • 31. import com.twitter.finagle.{Http,Service, Filter} import com.twitter.finagle.http.{Request,Response} import com.twitter.finagle.service.TimeoutFilter import com.twitter.util.MockTimer import com.twitter.conversions.time._ val httpClient: Service[Request, Response] = Http.client.newService("twitter.com") val timeoutFilter: Filter[Request, Response, Request, Response] = new TimeoutFilter[Request, Response](30.seconds, new MockTimer) val httpClientWithTimeout: Service[Request, Response] = timeoutFilter andThen httpClient Filter example http client WARNING This is only a showcase, timeouts for http clients are best configured by Http.client object How to implement this?
  • 32. Stacking filters recordHandletime andThen traceRequest andThen collectJvmStats andThen parseRequest andThen logRequest andThen recordClientStats andThen sanitize andThen respondToHealthCheck andThen applyTrafficControl andThen virtualHostServer Fronted webservers configuration at twitter:
  • 33. Cool client filters (or wannabe-filters) • MonitorFilter - handling exceptions • StatsFilter - exposing metrics • RetryFilter - retying calls with configured budget and a back-off policy • TimeoutFilter - mentioned earlier, for different aspects like idle time, request time, connection time ect. • LoadBalancing (not really a filter) - distributed load across nodes, just pass multiple host values • FailFast (not really a filter) - mark node as dead for a certain period of time
  • 34. • Unfortunately not all functionality can be expressed with Filters • Some things are a bit hairy - e.g. request cancelation • Beneath implementations is non-trivial but comprehensible • But the good part is that it all works out to the box for free with almost none configuration!
  • 35. There is more in Finagle to explore: • Thrift protocol • Mux - multiplexing RPC • ZooKeeper support • Network location naming
  • 37. Twitter Server • A “template” for finagle-based server • Flags • Logging • Metrics • Admin interface
  • 38. Flags (1) • Cmd line arguments passed to the application • A remedy to “How do I start this thing and what are the options?” • Smart with type inference and parsing capabilities
  • 39. Flags (2) val addr = flag("bind", new InetSocketAddress(0), "Bind address") val durations = flag("alarms", (1.second, 5.second), "2 alarm durations") $ java -jar target/myserver-1.0.0-SNAPSHOT.jar -help AdvancedServer -alarm_durations='1.seconds,5.seconds': 2 alarm durations -help='false': Show this help -admin.port=':9990': Admin http server port -bind=':0': Network interface to use -log.level='INFO': Log level -log.output='/dev/stderr': Output file -what='hello': String to return Option for fail fast when missing a flag
  • 40. Logging • Twitter server provides a logging trait • It can be configured with standard flags • Can be tuned on-the-fly
  • 42. Metrics • Defining own statistics • JVM stats • Processing and network stats
  • 43.
  • 44. Others • Linting your server for problems • Looking at threads • Profiling
  • 47. What is it? • Finatra is build atop Finagle and Twitter Server • Finatra does all the heavy-lifting that one needs to do when working only with Finagle
  • 48. Finatra features • Dependency injection using Guice • JSON handling with Jackson • Mustache support • Routing • Integrates it all together nicely
  • 49. package pl.tk.finagle.recommendation.controller import javax.inject.{Inject, Singleton} import com.twitter.finagle.http.Request import com.twitter.finagle.tracing.ClientTracingFilter.TracingFilter import com.twitter.finatra.http.Controller import com.twitter.finatra.request._ import com.twitter.inject.Logging import pl.tk.finagle.recommendation.engine.{RecommendationCmd, RecommendationEngine} case class RecommendationFromCookieRequest(@Inject request: Request, @RouteParam cookieId: Int, @RouteParam eshopId: Int, @Header `x-auth`: String) @Singleton class RecommendationController @Inject() (recommendationEngine: RecommendationEngine) extends Controller with Logging { get("/recommend/:eshop_id/:cookie_id") { r: RecommendationFromCookieRequest => infoResult("Hello") { TracingFilter("RecommendationEngine") andThen recommendationEngine apply RecommendationCmd(r.cookieId, r.eshopId) } } }
  • 50. Unified error reporting ➜ finagle-spike git:(master) ✗ curl -v 127.0.0.1:2001/recommend/32/wsf * Trying 127.0.0.1... * Connected to 127.0.0.1 (127.0.0.1) port 2001 (#0) > GET /recommend/32/wsf HTTP/1.1 > Host: 127.0.0.1:2001 > User-Agent: curl/7.43.0 > Accept: */* > < HTTP/1.1 400 Bad Request < Content-Type: application/json; charset=utf-8 < Server: Finatra < Date: Wed, 30 Mar 2016 07:05:53 +00:00 < Content-Length: 79 < * Connection #0 to host 127.0.0.1 left intact {"errors":["cookie_id: 'wsf' is not a valid int","x-auth: header is required"]}%
  • 51. JSON Support • Build on jackson-module-scala • Support for case classes (de)serlialization • Integrated with Joda • Error accumulation (instead of fail-fast) • Integration with routing • Most of the cases just return object
  • 52. Customizing Json class Server extends HttpServer { override def jacksonModule = CustomJacksonModule ... } object CustomJacksonModule extends FinatraJacksonModule { override val additionalJacksonModules = Seq( new SimpleModule { addSerializer(LocalDateParser) }) override val serializationInclusion = Include.NON_EMPTY override val propertyNamingStrategy = CamelCasePropertyNamingStrategy override def additionalMapperConfiguration(mapper: ObjectMapper) { mapper.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true) } }
  • 53. Validation import com.twitter.finatra.validation._ import org.joda.time.DateTime case class GroupRequest(@NotEmpty name: String, description: Option[String], tweetIds: Set[Long], dates: Dates) { @MethodValidation def validateName = { ValidationResult.validate( name.startsWith("grp-"), "name must start with 'grp-'") } } case class Dates(@PastTime start: DateTime, @PastTime end: DateTime) Also checked at routing time
  • 54. Testing (1) • Based on ScalaTest • Feature testing (both black box and white box) - looking at external interface of our service • Integration tests - only a subset of modules is instantiated and tested • Finatra does not provide anything for unit testing
  • 55. Testing (2) • Smart JSON diff • Integration with DI • Easy mocking • Embedded http server with our service
  • 57.
  • 58. What is it? • Distributed request tracing • Based on Google Dapper paper • Helps getting insight on how the services interact
  • 59.
  • 60. Zipkin Python pyramid_zipkin Pyramid Http (B3) Http (B3) Kafka | Scribe Yes py2, py3 support. Java brave Jersey, RestEASY, JAXRS2, Apache HttpClient, Mysql Http (B3) Http, Kafka, Scribe Yes Java 6 or higher Scala finagle-zipkin Finagle Http (B3), Thrift Scribe Yes Ruby zipkin-tracer Rack Http (B3) Http, Kafka, Scribe Yes lc support. Ruby 2.0 or higher C# ZipkinTracerM OWIN, Http (B3) Http Yes lc support. Not tied to finagle
  • 62. DEMO APP Recommendation ProductsService UserProfile 1 GetProducts 2 GetPromotedProducts GetUser CookieId, Eshop

Editor's Notes

  1. Name - host -grateful Finagle foundation of Twitter’s services Finagle - ease pain of distributed computing
  2. micorservices commond ground challanges/benefits
  3. People that raised their hand twice, are interesting
  4. Using old tools -> bad Guily of charge of doing this The same happens when you create services from scratch
  5. when I do a http post to some endpoint…bla bla bla. Run first services locally, the second one ect.
  6. Both are hard, finding and repairing that may involve many places where you need to make changes
  7. first time see - laugh hard single incomprehensible into multiple incomprehensible
  8. Funny thing is that simple languages thrive in micro services as you don’t need that much of a advanced constructs as single parts are small and should be exchangeable within two weeks
  9. Some of those could be addressed by framework your using The fallacies are The network is reliable. Latency is zero. Bandwidth is infinite. The network is secure. Topology doesn't change. There is one administrator. Transport cost is zero. The network is homogeneous.
  10. Big company - kilo-services
  11. Clustering - means closing inside technology.
  12. Don’t bend your model to the needs of your framework Adding field, removing field, making it optional
  13. Protocol angostic means it can be http but also memcache and mysql Finagle is low level
  14. Function that returns a A => Future
  15. Metoda mk vs apply + new
  16. We use the same base abstract building block for modeling both ends of the distributed So we can create utils that will work on both
  17. External traffic reverse proxy
  18. Future is immutable and one way flow.
  19. Network location naming - different protocols like DNS or ZK, with Dtab (delegation table) rewriting of the urls. We can delegate the request graph to rewrite some url to point to dev server Mux is a session-layer protocol, maximize bandwidth, avoid head-of-line blocking (response can get back out-of-order)