Spring Cloud
Gateway
@ntschutta
ntschutta.io
Nathaniel Schutta
https://content.pivotal.io/
ebooks/thinking-architecturally
Ah, microservices!
Kind of the in thing these days…
And everything that entails!
Lot of teams are adopting
microservices…
Only to discover some
assembly required.
Think about all the things a
cloud native app needs…
Service registry. Circuit breaker.
Config server. UAA.
Spring Cloud Services!
And, often, an API gateway.
What would you say that is?
Why would you need one?
What are my options?
Why should I consider Spring
Cloud Gateway?
Why do i need
A Gateway?
Remember the monolith?
It was a simpler time…
The Monolith
The
Browser
HTTP Request
HTTP Response
What is our target resolution?
Away we went!
Well, we’d argue
about some things…
But things changed.
The Monolith
The
Browser
HTTP Request
HTTP Response
The Monolith
(with a side of REST)
The
Browser
HTTP Request
Mobile
Apps
XML/JSON Res
HTTP Request
XML/JSON Res
You get an API, and *you* get
and API, and YOU get an API!
What caused this Cambrian
explosion of APIs?
Technology changes.
Reaction to monoliths and
heavy weight services.
As well as cloud environments.
https://mobile.twitter.com/linux/status/936877536780283905?lang=en
But it didn’t stop there…
Enter the microservice.
The Monolith
(with a side of REST)
The
Browser
HTTP Request
Mobile
Apps
XML/JSON Res
HTTP Request
XML/JSON Res
The
Browser
Mobile
Apps
Microservice
Microservice
Microservice
Microservice
Microservice
Before you know it…
http://evolutionaryarchitecture.com
Please Microservice Responsibly.
https://content.pivotal.io/blog/should-that-be-a-
microservice-keep-these-six-factors-in-mind
Shoot. What do we do now?
More architectural patterns,
more problems.
How do we facilitate
communication?
API Gateway pattern.
https://microservices.io/patterns/apigateway.html
Forces.
API granularity mismatch.
Different clients need different data!
Services are dynamic.
Backend for front-end variation.
Each client gets their own gateway.
Enter the API Gateway!
The
Browser
Mobile
Apps
Microservice
Microservice
Microservice
Microservice
Microservice
The
Browser
Mobile
Apps
Microservice
Microservice
Microservice
Microservice
Microservice
APIGateway
Gateways are not, in fact,
magic sparkle ponies...
Sorry about that.
Use them wisely.
Isn’t this just an ESB?
Saw that movie…know how it ends.
The principles of ESB aren’t bad.
Potential to recreate the
worst of the ESB era…
Single point of failure.
Tickets on top of tickets. With a
side of tickets. And more tickets.
Development bottleneck.
Feature bloat.
Doesn’t have to be that way!
Just a tool.
Gateway
Features
Routing.
Surgical Routing.
Canarying.
Resiliency.
Monolith Strangling.
https://www.martinfowler.com/bliki/StranglerApplication.html
Even better - data driven strangler.
https://content.pivotal.io/slides/strangling-the-
monolith-with-a-data-driven-approach-a-case-study
Security.
Monitoring.
Metrics.
Flexibility.
Decouple clients from endpoints.
End point per use case.
Rate limiting.
Rate limiting is easy right?
It is just X requests per second.
How do you actually enforce it?
Is it on the second boundary?
Straightforward on a single process.
But most apps are distributed
these days so…
Token bucket algorithm.
Two parameters: replenish rate
and burst capacity.
Tap is dripping “tokens”
into the bucket.
This is you’re replenish rate.
Requests come and pull
tokens out of the bucket.
If there are any!
If not?
429 Too Many Requests.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
Burst capacity is the
size of the bucket.
How many tokens will
this bucket hold?
Could have more tokens than
requests per second.
In other words, burst capacity is
larger than the replenish rate.
Can have “rollover tokens!”
Good enough for Stripe.
https://stripe.com/blog/rate-limiters
Spring Cloud Gateway brings
Stripe’s approach to you.
More on that in a minute…
Load balancing.
What does a reactive load
balancer look like exactly?
Many strategies are no better
than 2 random choices.
The Power of 2.
https://brooker.co.za/blog/2012/01/17/two-random.html
The Power of Two Choices in
Randomized Load Balancing.
https://www.eecs.harvard.edu/~michaelm/postscripts/tpds2001.pdf
Stale data leads to herd behavior.
Host A is quiet…
keep sending it traffic.
But now A is overloaded.
The LB doesn’t know it yet.
Next time it updates the cache,
A is overloaded…
So it goes quiet again.
Cycle back and forth. Quiet,
busy, quiet, busy…
There is another way.
Pick two hosts.
Forward to the least busy one.
Has the best of both worlds.
Uses current data.
Doesn’t suffer from
the herd behavior.
Throttling.
Request aggregation…
The list goes on!
Bit of a gray area here…
The line is fuzzy.
Don’t sneak any business logic
into your gateway!
Often want to modify the
request/response…
Don’t recreate the
worst of the ESB era.
Options
As you can guess, there is a
veritable plethora of options.
Appliances.
Can be hardware or virtual.
Act as a black box.
Low level.
F5, Apigee, CA API Gateway, etc.
SaaS solutions.
No management (for you).
Black box.
API driven.
Can be very pricey.
AWS Elastic Load Balancing, Apigee.
Work really well - when you are
running on the same cloud!
But if you aren’t…
Web Server.
Typically open source.
Reliable, proven.
Apache mod_proxy,
Nginx Kong, HA Proxy
Can be programmable
(often via C or Lua).
Service Mesh.
https://mobile.twitter.com/ntschutta/status/1024735701349355521
Happy Birthday Istio.
https://content.pivotal.io/blog/happy-birthday-istio-a-closer-look-at-how-pivotal-is-
embedding-the-service-mesh-to-cloud-foundry-kubernetes-and-knative
Service meshes are kind of all
the rage these days.
Distinction between east/west
and north/south routing.
East/west === internal.
Think app to app or app to
service. Container to container.
All within the family.
North/south also called ingress.
External traffic calling your services.
Aka from outside the family.
Meshes tend to be oriented
towards operations and platforms.
Very much “ops”, not
so much dev ops.
Istio, Envoy, LinkerD.
But no discussion would be
complete without mentioning…
Zuul.
You know, the
Gatekeeper of Gozer.
Came out of Netflix.
No one could have predicted this.
Zuul 1.
https://www.youtube.com/watch?v=mHHHpxJuTAo
Servlet based.
Blocking API.
Servlet 2.5 I/O.
No long lived connections.
Clunky API, not overly
developer friendly.
Can be tough to integrate.
Path based routing.
Number of proprietary features.
Early part of Spring Cloud.
Engineers at Netflix don’t just
sit around drinking espresso.
Zuul 2.
Lessons learned from Zuul 1.
It is *not* backwards compatible.
Non blocking I/O.
Originally written on RxNetty.
Rewritten to Netty primitives.
Supports HTTP/2.
Proprietary features.
https://mobile.twitter.com/agonigberg/status/914895239042740225
Zuul 2 : The Netflix Journey…
https://medium.com/netflix-techblog/zuul-2-the-netflix-journey-
to-asynchronous-non-blocking-systems-45947377fb5c
Many, many options.
Often very heavy weight.
Tickets on top of tickets. With a
side of tickets. And more tickets.
Embodies the negative connotation
of “enterprise software”.
It doesn’t have to be this way…
SC Gateway
A Spring approach to the
gateway problem!
Based on Spring 5,
Reactor and Boot 2.
Non blocking IO.
Backpressure.
Event loop!
Spring WebFlux.
Lives along side Spring MVC.
Non-blocking, reactive.
Streams!
HandlerMapping - what code is
going to handle this request.
WebFilter - manipulate the
request/response.
Predicate - test some
aspect of the request…
And determine whether to route it.
ServerWebExchange: access all
parts of the http request/response.
Configure routes in Java, YAML
or via repositories.
Can route on path, host,
headers, parameters…
Anything in the request.
Filters!
Rewrite path.
Add or remove request/
response headers.
Rate limiting.
Hystrix.
With so many options, why should
I use Spring Cloud Gateway?
It is programmer centric routing.
Antithesis of tickets with a side
of tickets. And more tickets.
Would you rather refresh a
configuration?
Or fill out another ticket?
Java centric, Spring centric.
You are in control.
Instead of one of these…
You can craft your own…
Except *you* decide what tools,
blades etc. you want.
Lightweight, simple.
Use it as you will. You aren’t
forced down a certain path.
Think of it as an ESB with
inversion of control.
It is not a SaaS, it is a tool.
You can’t just “run” SC Gateway.
It is just an app.
Developer focussed.
You know how to build
and run applications.
You build it, you push it.
It is in your hands, not some
random enterprise group.
Anything you could do in Zuul 1
is supported in SC Gateway.
But what about performance?
There was a benchmark
published in December 2017.
SC Gateway was not officially
released at that time.
There are no performance
issues today.
Many large companies rely on it.
Examples
Easy to add.
Use the starter:
org.springframework.cloud
Artifact id:
spring-cloud-starter-gateway
Route: basic building
block of the gateway.
ID, a destination URI, a collection of
predicates & a collection of filters.
If the aggregate predicate is
true, the route is matched.
Predicate: a Java 8
Function Predicate.
https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
Allows you to match on anything
from the HTTP request.
Filter: Instances Spring
Framework GatewayFilter.
https://cloud.spring.io/spring-cloud-gateway/single/
spring-cloud-gateway.html#_gatewayfilter_factories
Allows you to modify requests
and responses.
After predicate.
Cookies!
Path Route Predicate.
Multiple Route Predicate
Factories can be combined.
Logical and.
AddRequestParameter
GatewayFilter.
Hystrix GatewayFilter Factory.
The Hystrix filter can also accept an
optional fallbackUri parameter.
RedirectTo GatewayFilter.
RewritePath GatewayFilter.
Filters are distinct.
Single responsibility principal.
Add multiple filters to Route.
Global filters.
Spring Cloud
LoadBalancerClient.
WebSocket, Netty, Gateway Metrics.
You can mix and match.
Make it as complicated
as you’d like!
Fluent Java Routes API if you
prefer programmatic approach.
Very powerful, very useful!
Microservices are a useful
architectural pattern.
Like any design decision, there
are consequences.
But you knew that ;)
Gateways are useful.
Doesn’t have to devolve into a
blizzard of tickets!
Good luck!
September 24–27, 2018

Washington DC

Gaylord, National Harbor Discount Code

S1P200_NSchutta
Register
Today &
Save!
Nathaniel T. Schutta
@ntschutta
ntschutta.io
Thanks!
I’m a Software
Architect,
Now What?
with Nate Shutta
Modeling for
Software
Architects
with Nate Shutta
Presentation
Patterns
with Neal Ford & Nate Schutta

Spring Cloud Gateway - Nate Schutta