SlideShare ist ein Scribd-Unternehmen logo
1 von 32
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!

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
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 CSharpDhaval 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 unleashedJavier 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 - PraticalsFahad 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 8RichardWarburton
 
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-02Sven Ruppert
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
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
 
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 nodejsKaty Slemon
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 

Was ist angesagt? (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
 

Ähnlich wie 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 concurrencykshanth2101
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
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 wayOleg Podsechin
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - TransactionsDmitry Buzdin
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-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.pdfssuser6254411
 
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-MallaSpark Summit
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.ILEran Harel
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj 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
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 

Kürzlich hochgeladen (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

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/

Hinweis der Redaktion

  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