SlideShare a Scribd company logo
Finagle and Java Service Framework
@pavan
#service-framework
● Finagle Overview
● Programming with Futures
● Java Service Framework
Agenda
● Asynchronous, protocol-agnostic RPC framework for JVM languages
● Provides async client/server abstractions and hides low-level network details
of Netty
● Out of the box support for protocols such as HTTP, Thrift, Redis, Memcached
but can be extended
● Implemented in Scala
● Open-sourced by Twitter
Part 1. What is Finagle?
Blocking/Non-blocking/Asynchronous APIs
Blocking:
read(fd, …) // Thread is blocked until some data is available to read
Non Blocking:
read(fd, …) // Returns immediately either with data or EAGAIN
Asynchronous:
read(fd, callback(data),...)
Finagle Architecture
Netty:
Event-based
Low-level network I/O
Finagle:
Service-oriented,
Functional abstractions
[3] Thanks @vkostyukov for the diagram
Server Modules
● Servers are simple and optimized for high-throughput
Client Modules
Clients are tricky and have with the bulk of fault-tolerance logic. By default, they
are optimized for high success rate and low latency.
● Designed for handling workloads that have a mix of Compute and I/O.
● Each server can handle thousands of requests.
● Uses just two threads per core (Netty’s default, but its configurable).
How does it scale?
Programming with Futures
Part 2. Programming with Futures
● What is a Future?
○ A container to hold the value of async computation that may be either a
success or failure.
● History - Introduced as part of Java 1.5 java.util.concurrent.Future but had
limited functionality: isDone() and get() [blocking]
● Twitter Futures - Are more powerful and adds composability!
● Part of util-core package and not tied to any thread pool model.
Futures - continued
It’s a simple state machine
Pending
Failed
Succeeded
Done
How to consume Futures?
● Someone gives you a future, you act on it and pass it on (kinda hot potato)
Typical actions:
● Transform the value [map(), handle()]
● Log it, update stats [side-effect/callbacks - onSuccess(), onFailure()]
● Trigger another async computation and return that result [flatmap(), rescue()]
Most of the handlers are variations of the basic handler transform()
Future<B> transform(Function<Try<A>, Future<B>>);
Example 1
The backend I am calling returns an int, but I need to return a
string to my caller. What do I use?
Example 1
The backend I am calling returns an int, but I need to return a
string to my caller. What do I use?
Answer: map!
public Future<String> foo() {
return backend.foo().map(new Function<Integer, String>() {
public String apply(Integer i) {
return i.toString();
}
});
}
Example 1
The backend I am calling returns an int, but I need to return a
string to my caller. What do I use?
Answer: map!
import static com.twitter.util.Function.func;
public Future<String> foo() {
return backend.foo().map(func(i -> i.toString()));
}
Example 2
I consult a cache for a value, but on a miss, need to talk to a
database. What do I use?
Example 2
I consult a cache for a value, but on a miss, need to talk to a
database. What do I use?
Answer: flatmap!
public Future<Value> fetch(Key k) {
return cache.fetch(k).flatmap(
new Function<Value, Future<Value>>() {
public Future<Value> apply(Value v) {
if (v != null) return Future.value(v);
return db.fetch(k);
}
});
}
Handling Exceptions
● Don’t forget: map/flatmap will only execute for successful
futures
● To deal with exceptions: handle/rescue are the analogous
equivalent
Future<A> handle(Function<Throwable, A>)
Future<A> rescue(Function<Throwable, Future<A>>)
Example 1
If the backend I am calling throws an exception, I want to return
an error code. What do I use?
Example 1
If the backend I am calling throws an exception, I want to return
an error code. What do I use?
Answer: handle!
public Future<Result> foo() {
return backend.foo().handle(
new Function<Throwable, Result>() {
public Result apply(Throwable t) {
Result r = new Result();
r.setErrorCode(errorCodeFromThrowable(t));
return r;
}
});
Example 2
I consult a cache for a value, but if that failed, need to talk to a
database. What do I use?
Example 2
I consult a cache for a value, but if that failed, need to talk to a
database. What do I use?
Answer: rescue!
public Future<Value> get(Key k) {
return cache.fetch(k).rescue(
new Function<Throwable, Future<Value>>() {
public Future<Value> apply(Throwable t) {
LOG.error(“Cache lookup failed”, t);
return db.fetch(k)
}
});
}
Other handlers
More Sequential composition - join()
Concurrent composition, return after all are satisfied - collect()
Concurrent composition, return if any of the future is satisfied - select()
Finish within in a Timeout: within()
Delayed execuion: delayed()
Common Pitfalls
● Never block on a Future in production code (ok for unit tests)
○ Avoid future.get(), future.apply(), Await.result(future) as it ties up I/O processing threads and
it degrades Finagle’s performance considerably.
○ If you really need to block because you are dealing with synchronous libraries such as jdbc,
jedis use a dedicated FuturePool.
● Avoid ThreadLocal<T>. Use com.twitter.finagle.context.LocalContext instead
● Don't use parallel streams in Java 8
● Request concurrency leak - Never return “null” instead of Future<A>
Future<String> getPinJson(long pinId) {
return null; // This is bad!
// Use, return Future.value(null);
}
Part 3. Java Service Framework Features
Standardized Metrics - per client, per method success/fail counts and latency stats
Logging - slow log, exception log,
Rate limiting - Enforce quotas for clients
Genesis - Tool to generate the required stubs to bootstrap a finagle-thrift service
Warm up hook
Graceful shutdown
You need to enable your options via Proxy builder
ServiceFrameworkProxy<UserService.ServiceIface> serviceFrameworkProxy =
new ServiceFrameworkProxyBuilder<UserService.ServiceIface>()
.setHandler(serviceHandler)
.setServiceName(serviceName)
.setClusterName(serviceName.toLowerCase())
.setServerSetPath(serverSetPath)
.setClientNameProvider(new DefaultClientNameProvider())
.setRootLog(LOG)
.setFailureLog(FAILURE_LOG)
.enableExceptionTypeForFailureCount()
.disableLoggingForThrowable(ClientDiscardedRequestException.class)
.disableThrowablesAsServiceFailure(
Arrays.asList(ClientDiscardedRequestException.class,
DataValidationException.class))
.enableMethodNameForSuccessCountV2()
.enableMethodNameForFailureCountV2()
.enableMethodNameForResponseTimeMetricsV2()
.enableClientNameTagForSuccessCount()
.enableClientNameTagForFailureCount()
.enableClientNameTagForResponseTimeMetrics()
.enableExceptionLog()
.build();
Complaint 1:
● Clients are noticing higher latency or timeouts during deploys or restarts.
First few requests take longer than at steady state due to connection
establishment, Java’s Hopspot JIT etc.
Solution: Use warmUp hook and then join serverset
public static boolean warmUp(Callable<Boolean> warmUpCall)
// By default, invokes warmUpCall 100 times concurrently and expects it succeeds for at least 80%
of the calls
Graceful Shutdown
● Unjoin from serverset, waits for duration/2 secs and then tries to gracefully
shutdown server by draining existing requests within the remaining duration/2
secs
ServiceShutdownHook.register(server, Duration.fromSeconds(10), status)
public static void register(final Server server, final Duration gracePeriod,
final ServerSet.EndpointStatus endpointStatus)
Complaint 2:
Client is seeing rate limiting Exceptions even though rate limits are set to a high
value
Happens if the the server cluster is huge and the local rate limit per node becomes
small and the python client is running on few nodes (pinlater, offline job etc)
Solution: Try reducing max_connection_lifespan_ms if its python thriftmux client
Next steps
● Finagle upgrade to 6.43
○ Unlocks Retry Budgets
○ Defaults to P2C Load balancer instead of heap
○ Toggle between Netty3 and Netty4
○ Couple of performance fixes in Future scheduler
○ Many more...
Resources:
“Your server as a function” paper - https://dl.acm.org/citation.cfm?id=2525538
Source code: https://github.com/twitter/finagle
Finaglers - https://groups.google.com/d/forum/finaglers
Blogs:
[1] https://twitter.github.io/scala_school/finagle.html
[2] https://twitter.github.io/finagle/guide/developers/Futures.html
[3] http://vkostyukov.net/posts/finagle-101/
Thank you!

More Related Content

What's hot

Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
BoneyGawande
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
Javier Arias Losada
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
Mario Fusco
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
Fahad Shaikh
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02
Sven Ruppert
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
Suresh Loganatha
 
Java script
Java scriptJava script
Java script
Dhananjay Kumar
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
Trisha Gee
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
How to implement g rpc services in nodejs
How to implement g rpc services in nodejsHow to implement g rpc services in nodejs
How to implement g rpc services in nodejs
Katy Slemon
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 

What's hot (20)

Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Java script
Java scriptJava script
Java script
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
How to implement g rpc services in nodejs
How to implement g rpc services in nodejsHow to implement g rpc services in nodejs
How to implement g rpc services in nodejs
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 

Similar to Finagle and Java Service Framework at Pinterest

Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
dantleech
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
kshanth2101
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
Guy Korland
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
Almog Baku
 
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
Oleg Podsechin
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
Dongmin Yu
 
Data Pipeline at Tapad
Data Pipeline at TapadData Pipeline at Tapad
Data Pipeline at Tapad
Toby Matejovsky
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
NAVER D2
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - TransactionsDmitry Buzdin
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
Vincent Pradeilles
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdfProgramming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
ssuser6254411
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Spark Summit
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.IL
Eran Harel
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
ppd1961
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 

Similar to Finagle and Java Service Framework at Pinterest (20)

Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
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
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Data Pipeline at Tapad
Data Pipeline at TapadData Pipeline at Tapad
Data Pipeline at Tapad
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdfProgramming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
Programming For Big Data [ Submission DvcScheduleV2.cpp and StaticA.pdf
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.IL
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 

Recently uploaded

Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 

Recently uploaded (20)

Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 

Finagle and Java Service Framework at Pinterest

  • 1. Finagle and Java Service Framework @pavan #service-framework
  • 2. ● Finagle Overview ● Programming with Futures ● Java Service Framework Agenda
  • 3. ● Asynchronous, protocol-agnostic RPC framework for JVM languages ● Provides async client/server abstractions and hides low-level network details of Netty ● Out of the box support for protocols such as HTTP, Thrift, Redis, Memcached but can be extended ● Implemented in Scala ● Open-sourced by Twitter Part 1. What is Finagle?
  • 4. Blocking/Non-blocking/Asynchronous APIs Blocking: read(fd, …) // Thread is blocked until some data is available to read Non Blocking: read(fd, …) // Returns immediately either with data or EAGAIN Asynchronous: read(fd, callback(data),...)
  • 5. Finagle Architecture Netty: Event-based Low-level network I/O Finagle: Service-oriented, Functional abstractions [3] Thanks @vkostyukov for the diagram
  • 6. Server Modules ● Servers are simple and optimized for high-throughput
  • 7. Client Modules Clients are tricky and have with the bulk of fault-tolerance logic. By default, they are optimized for high success rate and low latency.
  • 8. ● Designed for handling workloads that have a mix of Compute and I/O. ● Each server can handle thousands of requests. ● Uses just two threads per core (Netty’s default, but its configurable). How does it scale?
  • 10. Part 2. Programming with Futures ● What is a Future? ○ A container to hold the value of async computation that may be either a success or failure. ● History - Introduced as part of Java 1.5 java.util.concurrent.Future but had limited functionality: isDone() and get() [blocking] ● Twitter Futures - Are more powerful and adds composability! ● Part of util-core package and not tied to any thread pool model.
  • 11. Futures - continued It’s a simple state machine Pending Failed Succeeded Done
  • 12. How to consume Futures? ● Someone gives you a future, you act on it and pass it on (kinda hot potato) Typical actions: ● Transform the value [map(), handle()] ● Log it, update stats [side-effect/callbacks - onSuccess(), onFailure()] ● Trigger another async computation and return that result [flatmap(), rescue()] Most of the handlers are variations of the basic handler transform() Future<B> transform(Function<Try<A>, Future<B>>);
  • 13. Example 1 The backend I am calling returns an int, but I need to return a string to my caller. What do I use?
  • 14. Example 1 The backend I am calling returns an int, but I need to return a string to my caller. What do I use? Answer: map! public Future<String> foo() { return backend.foo().map(new Function<Integer, String>() { public String apply(Integer i) { return i.toString(); } }); }
  • 15. Example 1 The backend I am calling returns an int, but I need to return a string to my caller. What do I use? Answer: map! import static com.twitter.util.Function.func; public Future<String> foo() { return backend.foo().map(func(i -> i.toString())); }
  • 16. Example 2 I consult a cache for a value, but on a miss, need to talk to a database. What do I use?
  • 17. Example 2 I consult a cache for a value, but on a miss, need to talk to a database. What do I use? Answer: flatmap! public Future<Value> fetch(Key k) { return cache.fetch(k).flatmap( new Function<Value, Future<Value>>() { public Future<Value> apply(Value v) { if (v != null) return Future.value(v); return db.fetch(k); } }); }
  • 18. Handling Exceptions ● Don’t forget: map/flatmap will only execute for successful futures ● To deal with exceptions: handle/rescue are the analogous equivalent Future<A> handle(Function<Throwable, A>) Future<A> rescue(Function<Throwable, Future<A>>)
  • 19. Example 1 If the backend I am calling throws an exception, I want to return an error code. What do I use?
  • 20. Example 1 If the backend I am calling throws an exception, I want to return an error code. What do I use? Answer: handle! public Future<Result> foo() { return backend.foo().handle( new Function<Throwable, Result>() { public Result apply(Throwable t) { Result r = new Result(); r.setErrorCode(errorCodeFromThrowable(t)); return r; } });
  • 21. Example 2 I consult a cache for a value, but if that failed, need to talk to a database. What do I use?
  • 22. Example 2 I consult a cache for a value, but if that failed, need to talk to a database. What do I use? Answer: rescue! public Future<Value> get(Key k) { return cache.fetch(k).rescue( new Function<Throwable, Future<Value>>() { public Future<Value> apply(Throwable t) { LOG.error(“Cache lookup failed”, t); return db.fetch(k) } }); }
  • 23. Other handlers More Sequential composition - join() Concurrent composition, return after all are satisfied - collect() Concurrent composition, return if any of the future is satisfied - select() Finish within in a Timeout: within() Delayed execuion: delayed()
  • 24. Common Pitfalls ● Never block on a Future in production code (ok for unit tests) ○ Avoid future.get(), future.apply(), Await.result(future) as it ties up I/O processing threads and it degrades Finagle’s performance considerably. ○ If you really need to block because you are dealing with synchronous libraries such as jdbc, jedis use a dedicated FuturePool. ● Avoid ThreadLocal<T>. Use com.twitter.finagle.context.LocalContext instead ● Don't use parallel streams in Java 8 ● Request concurrency leak - Never return “null” instead of Future<A> Future<String> getPinJson(long pinId) { return null; // This is bad! // Use, return Future.value(null); }
  • 25. Part 3. Java Service Framework Features Standardized Metrics - per client, per method success/fail counts and latency stats Logging - slow log, exception log, Rate limiting - Enforce quotas for clients Genesis - Tool to generate the required stubs to bootstrap a finagle-thrift service Warm up hook Graceful shutdown
  • 26. You need to enable your options via Proxy builder ServiceFrameworkProxy<UserService.ServiceIface> serviceFrameworkProxy = new ServiceFrameworkProxyBuilder<UserService.ServiceIface>() .setHandler(serviceHandler) .setServiceName(serviceName) .setClusterName(serviceName.toLowerCase()) .setServerSetPath(serverSetPath) .setClientNameProvider(new DefaultClientNameProvider()) .setRootLog(LOG) .setFailureLog(FAILURE_LOG) .enableExceptionTypeForFailureCount() .disableLoggingForThrowable(ClientDiscardedRequestException.class) .disableThrowablesAsServiceFailure( Arrays.asList(ClientDiscardedRequestException.class, DataValidationException.class)) .enableMethodNameForSuccessCountV2() .enableMethodNameForFailureCountV2() .enableMethodNameForResponseTimeMetricsV2() .enableClientNameTagForSuccessCount() .enableClientNameTagForFailureCount() .enableClientNameTagForResponseTimeMetrics() .enableExceptionLog() .build();
  • 27. Complaint 1: ● Clients are noticing higher latency or timeouts during deploys or restarts. First few requests take longer than at steady state due to connection establishment, Java’s Hopspot JIT etc. Solution: Use warmUp hook and then join serverset public static boolean warmUp(Callable<Boolean> warmUpCall) // By default, invokes warmUpCall 100 times concurrently and expects it succeeds for at least 80% of the calls
  • 28. Graceful Shutdown ● Unjoin from serverset, waits for duration/2 secs and then tries to gracefully shutdown server by draining existing requests within the remaining duration/2 secs ServiceShutdownHook.register(server, Duration.fromSeconds(10), status) public static void register(final Server server, final Duration gracePeriod, final ServerSet.EndpointStatus endpointStatus)
  • 29. Complaint 2: Client is seeing rate limiting Exceptions even though rate limits are set to a high value Happens if the the server cluster is huge and the local rate limit per node becomes small and the python client is running on few nodes (pinlater, offline job etc) Solution: Try reducing max_connection_lifespan_ms if its python thriftmux client
  • 30. Next steps ● Finagle upgrade to 6.43 ○ Unlocks Retry Budgets ○ Defaults to P2C Load balancer instead of heap ○ Toggle between Netty3 and Netty4 ○ Couple of performance fixes in Future scheduler ○ Many more...
  • 31. Resources: “Your server as a function” paper - https://dl.acm.org/citation.cfm?id=2525538 Source code: https://github.com/twitter/finagle Finaglers - https://groups.google.com/d/forum/finaglers Blogs: [1] https://twitter.github.io/scala_school/finagle.html [2] https://twitter.github.io/finagle/guide/developers/Futures.html [3] http://vkostyukov.net/posts/finagle-101/

Editor's Notes

  1. Server modules/ client modules
  2. history
  3. Internal state machine - Waiting, Interruptible, Transforming, Interrupted, Linked, and Done.
  4. How is a future fulfilled? Stack traces