SlideShare une entreprise Scribd logo
1  sur  44
Télécharger pour lire hors ligne
Trustin Lee, LINE
May 2019
Armeria
The Only Thrift · gRPC · REST
Microservice Framework You’ll Need
What is Armeria?
A user-friendly Java microservice framework
based on asynchronous and reactive model
with HTTP/2 and modern RPC protocols in mind
What is Armeria?
A user-friendly Java microservice framework
based on asynchronous and reactive model
with HTTP/2 and modern RPC protocols in mind
One fine day of
synchronous microservice
Shard 1
Shard 2
Shard 3
A bunch of
clients
Thread 1
Thread 2
Thread 3
Thread 4
Pending requests (Queue) Workers
Read
S1
Read
S2
Read
S3 Read
S1
Read
S2
Read
S3
Read
S1
Read
S2
Read
S3
Read
S1
Read
S2
Read
S3
Read
S2
Read
S3
Read
S1
Read
S1
Read
S2
Read
S3
Read
S1
… until Shard 2 ruins it.
Shard 1
Shard 2
Shard 3
A bunch of
clients
Thread 1
Thread 2
Thread 3
Thread 4
Pending requests (Queue) Workers
Read
S1
Read
S2
Read
S3 Read
S1
Read
S2
Read
S3
Read
S1
Read
S2
Read
S3
Read
S1
Read
S2
Read
S3
Read
S2
Read
S3
Read
S1
Read
S1
Read
S2
Read
S3
Read
S1
Timeout!
Shard 1 & 3: Why are no requests coming?
Workers: We’re busy waiting for Shard 2.
Shard 1
Shard 2
Shard 3
A bunch of
clients
Thread 1
Thread 2
Thread 3
Thread 4
Pending requests (Queue) Workers
Read
S1
Read
S2
Read
S3 Read
S1
Read
S2
Read
S3
Read
S1
Read
S2
Read
S3
Read
S1
Read
S2
Read
S3
Read
S2
Read
S3
Read
S1
Read
S2
Read
S2
Read
S2
Read
S2
Timeouts!Timeouts!Timeouts!Timeouts!
You can’t solve this with:
●
More CPUs
– They are very idle.
●
More threads
– They will all get stuck with Shard 2 in no time.
– Waste of CPU cycles – context switches are not free.
– Waste of memory – each thread needs its own stack.
●
Result:
– Fragile system that falls apart even on a tiny backend failure
– Inefficient system that takes more memory and CPU than what it actually needs
●
Maybe you can work around this, but you’ll have to keep tuning and adding hacks.
What is Armeria?
A user-friendly Java microservice framework
based on asynchronous and reactive model
with HTTP/2 and modern RPC protocols in mind
Problems with large payloads
●
We solved blocking problem with asynchronous programming,
but can we send 10MB personalized response to 100K clients?
– Can’t hold that much in RAM – 10MB × 100K = 1TB
●
What if we/they send too fast?
– Different bandwidth & processing power
●
We need ‘just enough buffering.’
– Expect OutOfMemoryError otherwise.
What is Armeria?
A user-friendly Java microservice framework
based on asynchronous and reactive model
with HTTP/2 and modern RPC protocols in mind
RPC vs. HTTP impedance mismatch
●
RPC has been hardly a 1st-class citizen in web frameworks.
– Method name
– Parameter names and values
– Return value or exception
POST /some_service HTTP/1.1
Host: example.com
Content-Length: 96
<binary request>
HTTP/1.1 200 OK
Host: example.com
Content-Length: 192
<binary response>
Failed RPC call
Access logs re-imagined
●
What if we provide access logs with …
– Universal API for gRPC · Thrift · REST
– RPC-level information
– Precise send · receive timings
●
Imagine streaming to data processing pipeline, e.g. Kafka.
192.167.1.2 - - [10/Oct/2000:13:55:36 -0700]
"POST /some_service HTTP/1.1" 200 2326
Making a debug call
●
Sending an ad-hoc query in RPC is hard.
– Find a proper service definition, e.g. .thrift or .proto files
– Set up code generator, build, IDE, etc.
– Write some code that makes an RPC call.
●
HTTP in contrast:
– cURL, telnet command, web-based tools and more.
●
There’s some effort to make things easier.
– gRPC reflection service + grpcurl
●
What if we build something more convenient and collaborative?
More than one RPC protocol
●
Supports both gRPC & Thrift …
– on a single HTTP port
– in a single JVM
– without any proxies?
●
Can serve non-RPC requests together.
– REST API – Static files
– Exposing metrics – Health-check requests from load balancers
– Traditional JEE webapps
●
Share common logic between different endpoints!
What is Armeria?
A user-friendly Java microservice framework
based on asynchronous and reactive model
with HTTP/2 and modern RPC protocols in mind
Better UX for devs
●
The last yet most important
●
Nobody wants a framework that’s hard to use.
●
Can we design …
– a user-friendly asynchronous API
– … with modest learning curve?
Our answer – Armeria
●
Asynchronous + High-performance
– Netty with JNI-based /dev/epoll transport and BoringSSL
●
Seamless integration with Reactive Streams
– RxJava2, Project Reactor, Spring WebFlux…
●
Ability to mix different types of services in a single server
– gRPC, Thrift, REST, Tomcat, Jetty…
●
Not just HTTP/2
– gRPC on HTTP/1
– HAProxy
●
Easy to learn and fun to use (hopefully)
Armeria by examples
HTTP · REST
Hello, world!
Server server = new ServerBuilder()
.http(8080)
.https(8443)
.tlsSelfSigned()
.haproxy(8080)
.service("/", (ctx, req) -> HttpResponse.of("Hello, world!"))
.build();
server.start();
Protocol auto-detection at 8080
Hello, world – Parameterized
Server server = new ServerBuilder()
.http(8080)
.service("/hello/:name",
(ctx, req) -> HttpResponse.of("Hello, %s!",
ctx.pathParam("name")))
.build();
server.start();
Hello, world – Annotated
Server server = new ServerBuilder()
.http(8080)
.annotatedService(new Object() {
@Get("/hello/:name")
public String hello(@Param String name) {
return String.format("Hello, %s!", name);
}
})
.build();
server.start();
There are more!
●
CompletableFuture and reactive responses
●
Query parameters and cookies
●
Request and response converters
●
Exception handlers
●
Content type negotiation
●
Regular-expression path mapping
●
Aims to be on-par or better than <your favorite web framework>
Armeria by examples
Thrift · gRPC
gRPC & Thrift basics
a. Write an IDL file – .proto or .thrift
b. A compiler compiles it into .java files.
c. Implement interfaces generated at ‘b’.
namespace java com.example
service HelloService {
string hello(1:string name)
}
syntax = "proto3";
package grpc.hello;
option java_package = "com.example";
service HelloService {
rpc Hello (HelloRequest)
returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
gRPC
Server server = new ServerBuilder()
.http(8080)
.service(new GrpcServiceBuilder().addService(new MyHelloService())
.build())
.build();
class MyHelloService extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void hello(HelloRequest req, StreamObserver<HelloReply> cb) {
HelloReply reply = HelloReply.newBuilder()
.setMessage("Hello, " + req.getName() + '!')
.build();
cb.onNext(reply);
cb.onCompleted();
}
}
Thrift
Server server = new ServerBuilder()
.http(8080)
.service("/hello", THttpService.of(new MyHelloService()))
.build();
class MyHelloService implements HelloService.AsyncIface {
@Override
public void hello(String name, AsyncMethodCallback<String> cb) {
cb.onComplete("Hello, " + name + '!');
}
}
What’s better than the official impls?
●
gRPC
– Works on both HTTP/1 and 2
– gRPC-Web support, i.e. can call gRPC services from JavaScript frontends
●
Thrift
– HTTP/2
– TTEXT (human-readable REST-ish JSON)
●
Can mix gRPC, Thrift, REST, Tomcat, Jetty, …
●
Can leverage the common Armeria features
– Decorators
– Web-based dashboard
Decorating services
Separation of concerns
a.k.a. filter, decorator, interceptor, middleware
Intercepting an HTTP request
THttpService.of(new MyHelloService())
.decorate((delegate, ctx, req) -> {
logger.info("{} Received a request", ctx);
HttpResponse res = delegate.serve(ctx, req);
res.completionFuture().thenAccept(unused -> {
logger.info("{} Sent a response", ctx);
});
return res;
})
●
Can’t access RPC information yet.
●
Need to decompose THttpService into:
– ThriftCallService – RPC layer
– THttpService – HTTP layer
Intercepting an RPC request
●
Complete access to the RPC call information
●
Override the parameters and methods
ThriftCallService.of(new MyHelloService())
.decorate((delegate, ctx, req) -> {
logger.info("{} Method: {}, Params: {}",
ctx, req.method(), req.params());
RpcResponse res = delegate.serve(ctx, req);
res.thenAccept(value -> {
logger.info("{} Result: {}", ctx, value);
});
return res;
})
.decorate(THttpService.newDecorator())
Decorator as core extension mechanism
●
Request throttling
●
Metric collection
●
Distributed tracing (Zipkin)
●
HTTP content encoding
●
HTTP authn/z
●
CORS policies
●
Circuit breakers
●
Automatic retries
●
…
Distributed tracing with Zipkin
import brave.Tracing;
import brave.propagation.CurrentTraceContext;
import brave.sampler.Sampler;
Server server = new ServerBuilder()
.http(8080)
.service("/my_service",
myService.decorate(
HttpTracingService.newDecorator(
Tracing.newBuilder()
.currentTraceContext(CurrentTraceContext.Default.create())
.localServiceName("myService")
.spanReporter(spanReporter)
.sampler(Sampler.create(/* 5% */ 0.05f))
.build())))
.build();
Playing better with RPC
Armeria documentation service
Armeria documentation service
●
Enabled by adding DocService to ServerBuilder
●
Browse and invoke RPC services in an Armeria server
– No fiddling with binary payloads
– Send a request without writing code
●
Supports gRPC, Thrift and annotated services
●
We have a plan to add:
– Metric monitoring console
– Runtime configuration editor, e.g. logger level
●
Share the URL to reproduce a call.
All pieces together
The ultimate all-in-one micro service
ServerBuilder sb = new ServerBuilder();
// Thrift services
sb.service("/thrift/foo", THttpService.of(myThriftFooService));
sb.service("/thrift/bar", THttpService.of(myThriftBarService));
// gRPC services
sb.service(new GrpcServiceBuilder().addService(myGrpcFooService)
.addService(myGrpcBarService)
.build());
// Static files
sb.service("prefix:/files", HttpFileService.forFileSystem("htdocs"));
// Legacy webapps
sb.service("prefix:/webapp/foo", TomcatService.forFileSystem("foo.war"));
sb.service("prefix:/webapp/bar", TomcatService.forFileSystem("bar.war"));
// Documentation service
sb.service("prefix:/internal/docs", new DocService());
// L7 health check service
sb.service("/internal/healthcheck", new HttpHealthCheckService());
// Prometheus exposition
sb.service("/internal/prometheus", new PrometheusExpositionService(...));
// Enable logging for all services.
sb.decorator(LoggingService.newDecorator());
// Enable distributed tracing for all services.
sb.decorator(HttpTracingService.newDecorator(...));
// Send all access logs to Kafka.
sb.accessLogWriter(new KafkaAccessLogWriter(...), true);
What about client-side?
Armeria client API
●
Similar experience to the server-side API
– e.g. Common types, Decorators, RPC-friendliness
●
Client-specific stuff
– Circuit breakers
– Automatic retries
– Client-side load balancing
– Retrofit integration – https://square.github.io/retrofit/
// Send DNS queries periodically to discover service hosts (k8s style).
DnsServiceEndpointGroup group =
DnsServiceEndpointGroup.of("my-service.cluster.local");
// Register the group into the registry.
EndpointGroupRegistry.register("myService", group,
EndpointSelectionStrategy.WEIGHTED_ROUND_ROBIN);
// Create a new HTTP client that connects to the group
// with retries, circuit breaker and logging.
HttpClient client = new HttpClientBuilder("http://group:myService")
.decorator(RetryingHttpClient.newDecorator(onServerErrorStatus()))
.decorator(CircuitBreakerHttpClient.newDecorator(...))
.decorator(LoggingClient.newDecorator())
.build();
// Send a request and print the response content.
client.get("/greet").aggregate()
.thenAccept(res -> System.out.println(res.contentUtf8()))
.exceptionally(cause -> { /* Handle an error. */ });
Got interested?
Let’s build Armeria together!
●
Give it a try.
●
Ask questions.
●
Request new features.
●
Tell us what rocks and sucks.
●
Consider joining the effort.
Meet us at GitHub and Slack
●
https://github.com/line/armeria
●
https://line-slacknow.herokuapp.com/line-armeria/

Contenu connexe

Plus de J On The Beach

The big data Universe. Literally.
The big data Universe. Literally.The big data Universe. Literally.
The big data Universe. Literally.J On The Beach
 
Streaming to a New Jakarta EE
Streaming to a New Jakarta EEStreaming to a New Jakarta EE
Streaming to a New Jakarta EEJ On The Beach
 
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...J On The Beach
 
Pushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and BlazorPushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and BlazorJ On The Beach
 
Axon Server went RAFTing
Axon Server went RAFTingAxon Server went RAFTing
Axon Server went RAFTingJ On The Beach
 
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...J On The Beach
 
Madaari : Ordering For The Monkeys
Madaari : Ordering For The MonkeysMadaari : Ordering For The Monkeys
Madaari : Ordering For The MonkeysJ On The Beach
 
Servers are doomed to fail
Servers are doomed to failServers are doomed to fail
Servers are doomed to failJ On The Beach
 
Interaction Protocols: It's all about good manners
Interaction Protocols: It's all about good mannersInteraction Protocols: It's all about good manners
Interaction Protocols: It's all about good mannersJ On The Beach
 
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...J On The Beach
 
Leadership at every level
Leadership at every levelLeadership at every level
Leadership at every levelJ On The Beach
 
Machine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind LibrariesMachine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind LibrariesJ On The Beach
 
Getting started with Deep Reinforcement Learning
Getting started with Deep Reinforcement LearningGetting started with Deep Reinforcement Learning
Getting started with Deep Reinforcement LearningJ On The Beach
 
Toward Predictability and Stability At The Edge Of Chaos
Toward Predictability and Stability At The Edge Of ChaosToward Predictability and Stability At The Edge Of Chaos
Toward Predictability and Stability At The Edge Of ChaosJ On The Beach
 
Numeric programming with spire
Numeric programming with spireNumeric programming with spire
Numeric programming with spireJ On The Beach
 
Istio Service Mesh & pragmatic microservices architecture
Istio Service Mesh & pragmatic microservices architectureIstio Service Mesh & pragmatic microservices architecture
Istio Service Mesh & pragmatic microservices architectureJ On The Beach
 
GraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster EverywhereGraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster EverywhereJ On The Beach
 
Continuous delivery in the real world
Continuous delivery in the real world Continuous delivery in the real world
Continuous delivery in the real world J On The Beach
 
Free the Functions with Fn project!
Free the Functions with Fn project!Free the Functions with Fn project!
Free the Functions with Fn project!J On The Beach
 
Leveraging AI for facilitating refugee integration
Leveraging AI for facilitating refugee integrationLeveraging AI for facilitating refugee integration
Leveraging AI for facilitating refugee integrationJ On The Beach
 

Plus de J On The Beach (20)

The big data Universe. Literally.
The big data Universe. Literally.The big data Universe. Literally.
The big data Universe. Literally.
 
Streaming to a New Jakarta EE
Streaming to a New Jakarta EEStreaming to a New Jakarta EE
Streaming to a New Jakarta EE
 
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
 
Pushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and BlazorPushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and Blazor
 
Axon Server went RAFTing
Axon Server went RAFTingAxon Server went RAFTing
Axon Server went RAFTing
 
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
 
Madaari : Ordering For The Monkeys
Madaari : Ordering For The MonkeysMadaari : Ordering For The Monkeys
Madaari : Ordering For The Monkeys
 
Servers are doomed to fail
Servers are doomed to failServers are doomed to fail
Servers are doomed to fail
 
Interaction Protocols: It's all about good manners
Interaction Protocols: It's all about good mannersInteraction Protocols: It's all about good manners
Interaction Protocols: It's all about good manners
 
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
 
Leadership at every level
Leadership at every levelLeadership at every level
Leadership at every level
 
Machine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind LibrariesMachine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind Libraries
 
Getting started with Deep Reinforcement Learning
Getting started with Deep Reinforcement LearningGetting started with Deep Reinforcement Learning
Getting started with Deep Reinforcement Learning
 
Toward Predictability and Stability At The Edge Of Chaos
Toward Predictability and Stability At The Edge Of ChaosToward Predictability and Stability At The Edge Of Chaos
Toward Predictability and Stability At The Edge Of Chaos
 
Numeric programming with spire
Numeric programming with spireNumeric programming with spire
Numeric programming with spire
 
Istio Service Mesh & pragmatic microservices architecture
Istio Service Mesh & pragmatic microservices architectureIstio Service Mesh & pragmatic microservices architecture
Istio Service Mesh & pragmatic microservices architecture
 
GraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster EverywhereGraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster Everywhere
 
Continuous delivery in the real world
Continuous delivery in the real world Continuous delivery in the real world
Continuous delivery in the real world
 
Free the Functions with Fn project!
Free the Functions with Fn project!Free the Functions with Fn project!
Free the Functions with Fn project!
 
Leveraging AI for facilitating refugee integration
Leveraging AI for facilitating refugee integrationLeveraging AI for facilitating refugee integration
Leveraging AI for facilitating refugee integration
 

Dernier

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
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
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
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
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
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
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 

Dernier (20)

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
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
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
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
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
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...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 

Armeria: The Only Thrift/gRPC/REST Microservice Framework You'll Need

  • 1. Trustin Lee, LINE May 2019 Armeria The Only Thrift · gRPC · REST Microservice Framework You’ll Need
  • 2. What is Armeria? A user-friendly Java microservice framework based on asynchronous and reactive model with HTTP/2 and modern RPC protocols in mind
  • 3. What is Armeria? A user-friendly Java microservice framework based on asynchronous and reactive model with HTTP/2 and modern RPC protocols in mind
  • 4. One fine day of synchronous microservice Shard 1 Shard 2 Shard 3 A bunch of clients Thread 1 Thread 2 Thread 3 Thread 4 Pending requests (Queue) Workers Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S2 Read S3 Read S1 Read S1 Read S2 Read S3 Read S1
  • 5. … until Shard 2 ruins it. Shard 1 Shard 2 Shard 3 A bunch of clients Thread 1 Thread 2 Thread 3 Thread 4 Pending requests (Queue) Workers Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S2 Read S3 Read S1 Read S1 Read S2 Read S3 Read S1 Timeout!
  • 6. Shard 1 & 3: Why are no requests coming? Workers: We’re busy waiting for Shard 2. Shard 1 Shard 2 Shard 3 A bunch of clients Thread 1 Thread 2 Thread 3 Thread 4 Pending requests (Queue) Workers Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S1 Read S2 Read S3 Read S2 Read S3 Read S1 Read S2 Read S2 Read S2 Read S2 Timeouts!Timeouts!Timeouts!Timeouts!
  • 7. You can’t solve this with: ● More CPUs – They are very idle. ● More threads – They will all get stuck with Shard 2 in no time. – Waste of CPU cycles – context switches are not free. – Waste of memory – each thread needs its own stack. ● Result: – Fragile system that falls apart even on a tiny backend failure – Inefficient system that takes more memory and CPU than what it actually needs ● Maybe you can work around this, but you’ll have to keep tuning and adding hacks.
  • 8. What is Armeria? A user-friendly Java microservice framework based on asynchronous and reactive model with HTTP/2 and modern RPC protocols in mind
  • 9. Problems with large payloads ● We solved blocking problem with asynchronous programming, but can we send 10MB personalized response to 100K clients? – Can’t hold that much in RAM – 10MB × 100K = 1TB ● What if we/they send too fast? – Different bandwidth & processing power ● We need ‘just enough buffering.’ – Expect OutOfMemoryError otherwise.
  • 10. What is Armeria? A user-friendly Java microservice framework based on asynchronous and reactive model with HTTP/2 and modern RPC protocols in mind
  • 11. RPC vs. HTTP impedance mismatch ● RPC has been hardly a 1st-class citizen in web frameworks. – Method name – Parameter names and values – Return value or exception POST /some_service HTTP/1.1 Host: example.com Content-Length: 96 <binary request> HTTP/1.1 200 OK Host: example.com Content-Length: 192 <binary response> Failed RPC call
  • 12. Access logs re-imagined ● What if we provide access logs with … – Universal API for gRPC · Thrift · REST – RPC-level information – Precise send · receive timings ● Imagine streaming to data processing pipeline, e.g. Kafka. 192.167.1.2 - - [10/Oct/2000:13:55:36 -0700] "POST /some_service HTTP/1.1" 200 2326
  • 13. Making a debug call ● Sending an ad-hoc query in RPC is hard. – Find a proper service definition, e.g. .thrift or .proto files – Set up code generator, build, IDE, etc. – Write some code that makes an RPC call. ● HTTP in contrast: – cURL, telnet command, web-based tools and more. ● There’s some effort to make things easier. – gRPC reflection service + grpcurl ● What if we build something more convenient and collaborative?
  • 14. More than one RPC protocol ● Supports both gRPC & Thrift … – on a single HTTP port – in a single JVM – without any proxies? ● Can serve non-RPC requests together. – REST API – Static files – Exposing metrics – Health-check requests from load balancers – Traditional JEE webapps ● Share common logic between different endpoints!
  • 15. What is Armeria? A user-friendly Java microservice framework based on asynchronous and reactive model with HTTP/2 and modern RPC protocols in mind
  • 16. Better UX for devs ● The last yet most important ● Nobody wants a framework that’s hard to use. ● Can we design … – a user-friendly asynchronous API – … with modest learning curve?
  • 17. Our answer – Armeria ● Asynchronous + High-performance – Netty with JNI-based /dev/epoll transport and BoringSSL ● Seamless integration with Reactive Streams – RxJava2, Project Reactor, Spring WebFlux… ● Ability to mix different types of services in a single server – gRPC, Thrift, REST, Tomcat, Jetty… ● Not just HTTP/2 – gRPC on HTTP/1 – HAProxy ● Easy to learn and fun to use (hopefully)
  • 19. Hello, world! Server server = new ServerBuilder() .http(8080) .https(8443) .tlsSelfSigned() .haproxy(8080) .service("/", (ctx, req) -> HttpResponse.of("Hello, world!")) .build(); server.start(); Protocol auto-detection at 8080
  • 20. Hello, world – Parameterized Server server = new ServerBuilder() .http(8080) .service("/hello/:name", (ctx, req) -> HttpResponse.of("Hello, %s!", ctx.pathParam("name"))) .build(); server.start();
  • 21. Hello, world – Annotated Server server = new ServerBuilder() .http(8080) .annotatedService(new Object() { @Get("/hello/:name") public String hello(@Param String name) { return String.format("Hello, %s!", name); } }) .build(); server.start();
  • 22. There are more! ● CompletableFuture and reactive responses ● Query parameters and cookies ● Request and response converters ● Exception handlers ● Content type negotiation ● Regular-expression path mapping ● Aims to be on-par or better than <your favorite web framework>
  • 24. gRPC & Thrift basics a. Write an IDL file – .proto or .thrift b. A compiler compiles it into .java files. c. Implement interfaces generated at ‘b’. namespace java com.example service HelloService { string hello(1:string name) } syntax = "proto3"; package grpc.hello; option java_package = "com.example"; service HelloService { rpc Hello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
  • 25. gRPC Server server = new ServerBuilder() .http(8080) .service(new GrpcServiceBuilder().addService(new MyHelloService()) .build()) .build(); class MyHelloService extends HelloServiceGrpc.HelloServiceImplBase { @Override public void hello(HelloRequest req, StreamObserver<HelloReply> cb) { HelloReply reply = HelloReply.newBuilder() .setMessage("Hello, " + req.getName() + '!') .build(); cb.onNext(reply); cb.onCompleted(); } }
  • 26. Thrift Server server = new ServerBuilder() .http(8080) .service("/hello", THttpService.of(new MyHelloService())) .build(); class MyHelloService implements HelloService.AsyncIface { @Override public void hello(String name, AsyncMethodCallback<String> cb) { cb.onComplete("Hello, " + name + '!'); } }
  • 27. What’s better than the official impls? ● gRPC – Works on both HTTP/1 and 2 – gRPC-Web support, i.e. can call gRPC services from JavaScript frontends ● Thrift – HTTP/2 – TTEXT (human-readable REST-ish JSON) ● Can mix gRPC, Thrift, REST, Tomcat, Jetty, … ● Can leverage the common Armeria features – Decorators – Web-based dashboard
  • 28. Decorating services Separation of concerns a.k.a. filter, decorator, interceptor, middleware
  • 29. Intercepting an HTTP request THttpService.of(new MyHelloService()) .decorate((delegate, ctx, req) -> { logger.info("{} Received a request", ctx); HttpResponse res = delegate.serve(ctx, req); res.completionFuture().thenAccept(unused -> { logger.info("{} Sent a response", ctx); }); return res; }) ● Can’t access RPC information yet. ● Need to decompose THttpService into: – ThriftCallService – RPC layer – THttpService – HTTP layer
  • 30. Intercepting an RPC request ● Complete access to the RPC call information ● Override the parameters and methods ThriftCallService.of(new MyHelloService()) .decorate((delegate, ctx, req) -> { logger.info("{} Method: {}, Params: {}", ctx, req.method(), req.params()); RpcResponse res = delegate.serve(ctx, req); res.thenAccept(value -> { logger.info("{} Result: {}", ctx, value); }); return res; }) .decorate(THttpService.newDecorator())
  • 31. Decorator as core extension mechanism ● Request throttling ● Metric collection ● Distributed tracing (Zipkin) ● HTTP content encoding ● HTTP authn/z ● CORS policies ● Circuit breakers ● Automatic retries ● …
  • 32. Distributed tracing with Zipkin import brave.Tracing; import brave.propagation.CurrentTraceContext; import brave.sampler.Sampler; Server server = new ServerBuilder() .http(8080) .service("/my_service", myService.decorate( HttpTracingService.newDecorator( Tracing.newBuilder() .currentTraceContext(CurrentTraceContext.Default.create()) .localServiceName("myService") .spanReporter(spanReporter) .sampler(Sampler.create(/* 5% */ 0.05f)) .build()))) .build();
  • 33. Playing better with RPC Armeria documentation service
  • 34. Armeria documentation service ● Enabled by adding DocService to ServerBuilder ● Browse and invoke RPC services in an Armeria server – No fiddling with binary payloads – Send a request without writing code ● Supports gRPC, Thrift and annotated services ● We have a plan to add: – Metric monitoring console – Runtime configuration editor, e.g. logger level
  • 35.
  • 36. ● Share the URL to reproduce a call.
  • 37. All pieces together The ultimate all-in-one micro service
  • 38. ServerBuilder sb = new ServerBuilder(); // Thrift services sb.service("/thrift/foo", THttpService.of(myThriftFooService)); sb.service("/thrift/bar", THttpService.of(myThriftBarService)); // gRPC services sb.service(new GrpcServiceBuilder().addService(myGrpcFooService) .addService(myGrpcBarService) .build()); // Static files sb.service("prefix:/files", HttpFileService.forFileSystem("htdocs")); // Legacy webapps sb.service("prefix:/webapp/foo", TomcatService.forFileSystem("foo.war")); sb.service("prefix:/webapp/bar", TomcatService.forFileSystem("bar.war")); // Documentation service sb.service("prefix:/internal/docs", new DocService()); // L7 health check service sb.service("/internal/healthcheck", new HttpHealthCheckService()); // Prometheus exposition sb.service("/internal/prometheus", new PrometheusExpositionService(...)); // Enable logging for all services. sb.decorator(LoggingService.newDecorator()); // Enable distributed tracing for all services. sb.decorator(HttpTracingService.newDecorator(...)); // Send all access logs to Kafka. sb.accessLogWriter(new KafkaAccessLogWriter(...), true);
  • 40. Armeria client API ● Similar experience to the server-side API – e.g. Common types, Decorators, RPC-friendliness ● Client-specific stuff – Circuit breakers – Automatic retries – Client-side load balancing – Retrofit integration – https://square.github.io/retrofit/
  • 41. // Send DNS queries periodically to discover service hosts (k8s style). DnsServiceEndpointGroup group = DnsServiceEndpointGroup.of("my-service.cluster.local"); // Register the group into the registry. EndpointGroupRegistry.register("myService", group, EndpointSelectionStrategy.WEIGHTED_ROUND_ROBIN); // Create a new HTTP client that connects to the group // with retries, circuit breaker and logging. HttpClient client = new HttpClientBuilder("http://group:myService") .decorator(RetryingHttpClient.newDecorator(onServerErrorStatus())) .decorator(CircuitBreakerHttpClient.newDecorator(...)) .decorator(LoggingClient.newDecorator()) .build(); // Send a request and print the response content. client.get("/greet").aggregate() .thenAccept(res -> System.out.println(res.contentUtf8())) .exceptionally(cause -> { /* Handle an error. */ });
  • 43. Let’s build Armeria together! ● Give it a try. ● Ask questions. ● Request new features. ● Tell us what rocks and sucks. ● Consider joining the effort.
  • 44. Meet us at GitHub and Slack ● https://github.com/line/armeria ● https://line-slacknow.herokuapp.com/line-armeria/