SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Rachel Reese Jet.com
@rachelreese @JetTechnology
Patterns and Practices for
Real-world Event-driven
Microservices
Real-world
We plan to be the new Amazon.com
Launched July 22, 2015
• Both Apple & Android named our app
as one of their top 5 for 2015
• Over 20k orders per day
• Over 10.5 million SKUs
• #4 marketplace worldwide
• 700 microservices
We’re hiring!
http://jet.com/about-us/working-at-jet
Azure Web sites
Cloud
services VMs Service bus
queues
Services
bus topics
Blob storage
Table
storage Queues Hadoop DNS Active
directory
SQL Azure R
F# Paket FSharp.Data Chessie Unquote SQLProvider Python
Deedle
FAK
E
FSharp.Async React Node Angular SAS
Storm Elastic
Search
Xamarin Microservices Consul Kafka PDW
Splunk Redis SQL Puppet Jenkins
Apache
Hive
EventStore
Microservices
Microservices
An application of the single responsibility principle at the service level.
Has an input, produces an output.
Easy scalability
Independent releasability
More even distribution of complexity
Benefits
“A class should have one, and only one, reason to change.”
Event-driven
Event-driven
The focus of your
application code is to react to
events (single or a stream).
Events
Any significant change in
state that has happened
in your domain
• Past tense
• Immutable
• Contains only relevant
data to transaction
All events should be represented as
verbs in the past tense such as
CustomerRelocated,
CargoShipped, or
InventoryLossageRecorded.
For those who speak French, it should be
passé composé, they are things that have
completed in the past.
Greg Young
Event
Consumer
“Events” as the notification messages
Event channelEvent
Emitter
Microservice input should be treated as
an Observable
Events should be an Observable
Event-driven is Reactive
Does anyone here use Rx?
Event-sourced
Compare to relational
model which captures
only the latest state
change. These sets
are then related to
each other.
Event-sourced
• Event-sourced is about how you model the domain.
• An append-only sequence of events as data store.
• Keep track of all state changes.
• Can REPLAY these event streams.
Event Stream
How did Jet decide on microservices?
Why F#?
FP |> Programmers <3
Why F#? Productivity
The F# solution offers us an order of magnitude
increase in productivity and allows one developer to
perform the work [of] a team of dedicated
developers…
Yan Cui
Lead Server Engineer, Gamesys
“
“ “
Why F#? Expanded feature set
Expanded feature set: Option types
Why F#? Concise & powerful code
Concise & powerful code
public abstract class Transport{ }
public abstract class Car : Transport {
public string Make { get; private set; }
public string Model { get; private set; }
public Car (string make, string model) {
this.Make = make;
this.Model = model;
}
}
public abstract class Bus : Transport {
public int Route { get; private set; }
public Bus (int route) {
this.Route = route;
}
}
public class Bicycle: Transport {
public Bicycle() {
}
}
type Transport =
| Car of Make:string * Model:string
| Bus of Route:int
| Bicycle
C# F#
Trivial to pattern match on!
F#patternmatching
C#
Concise & powerful code
public abstract class Transport{ }
public abstract class Car : Transport {
public string Make { get; private set; }
public string Model { get; private set; }
public Car (string make, string model) {
this.Make = make;
this.Model = model;
}
}
public abstract class Bus : Transport {
public int Route { get; private set; }
public Bus (int route) {
this.Route = route;
}
}
public class Bicycle: Transport {
public Bicycle() {
}
}
type Transport =
| Car of Make:string * Model:string
| Bus of Route:int
| Bicycle
| Train of Line:int
let getThereVia (transport:Transport) =
match transport with
| Car (make,model) -> ...
| Bus route -> ...
| Bicycle -> ...
Warning FS0025: Incomplete pattern
matches on this expression. For example,
the value ’Train' may indicate a case not
covered by the pattern(s)
C# F#
Why F#? Readability
type Booking =
| Basic of Plane
| Combo of Combo
| FullPack of Plane * Hotel * Car
and Plane = {Outbound: DateTime; Return: DateTime; Destination: Country}
and Combo =
| ``With Hotel`` of Plane * Hotel
| ``With Car`` of Plane * Car
and Hotel = {Arrival: DateTime; Departure: DateTime; Location: Country}
and Car = {From: DateTime; To: DateTime; Location: Country}
and Country = {Name: String; ``ISO 3166-1``: char*char}
Original code
Refactored, clean code
F# way 33
type Year = int
type [<Measure>] percent
type Customer = Simple | Valuable | MostValuable
type AccountStatus =
| Registered of Customer * since:Year
| Unregistered
let customerDiscount = function
| Simple -> 1<percent>
| Valuable -> 3<percent>
| MostValuable -> 5<percent>
let yearsDiscount = function
| years when years > 5 -> 5<percent>
| years -> 1<percent> * years
let accountDiscount = function
| Registered (customer, years) ->
customerDiscount customer, yearsDiscount years
| Unregistered -> 0<percent>, 0<percent>
let asPercent p = decimal p / 100m
let reducePriceBy discount price =
price - price * (asPercent discount)
let calculateDiscountedPrice price account =
let custDiscount, yrsDiscount =
accountDiscount account
price
|> reducePriceBy custDiscount
|> reducePriceBy yrsDiscount
Guidelines
Be functional!
Prefer immutability
Avoid state changes,
side effects, and
mutable data
Use data in  data out
transformations
Think about mapping
inputs to outputs.
Look at problems
recursively
Consider successively
smaller chunks of the
same problem
Treat functions as
unit of work
Higher-order functions
Don’t abstract
This one magical service could write to ALL of the following:
…badly.
Event
store
Nservice
Bus
MSMQ 0MQ
SQL
Server
Isolate side effects
Submit order
microservice
Insert order to
SQL microservice
Send thank you
email microservice
Updates SQL
Sends “Thank you for
ordering” Email
Updates SQL
Sends “Thank you for
ordering” Email
Use a backup service to replay events
Service 1 runs in production as normal
Backup service 1 replays events until up-to-date.
Switch over. Instantly live with changes!
Also stage a copy of any aggregate/data store
until stream has completed replaying!
type Input =
| Product of Product
type Output =
| ProductPriceNile of Product * decimal
| ProductPriceCheckFailed of PriceCheckFailed
let handle (input:Input) =
async {
return Some(ProductPriceNile({Sku="343434"; ProductId = 17; ProductDescription = "My
amazing product"; CostPer=1.96M}, 3.96M))
}
let interpret id output =
match output with
| Some (Output.ProductPriceNile (e, price)) -> async {()} // write to event store
| Some (Output.ProductPriceCheckFailed e) -> async {()} // log failure
| None -> async {{ }} // log failure
let consume = EventStoreQueue.consume (decodeT Input.Product) handle interpret
What do our services look like?
Define inputs
& outputs
Define how input
transforms to output
Define what to do
with output
Read events,
handle, & interpret
Microservices should not control own lifecycle
Execution
runtime
Deployment Configuration Restarting
Versioning Scaling Availability
Grouping by
subsystem
Scheduling
Input-output
static analysis
Dashboard
Think
IoC!
Torch YAML files
torchVer: 2.0.0
subSystem: PriceCheck
name: PriceCheck
description: checks prices on nile
ver: 0.0.1
autoStart: always
compile: true
ha: aa ##active-active. Could be ap for active-passive
scriptPath: PriceCheckNilePriceCheckNile.fsx
libPath: binrelease
args: --jsonConfig=PriceCheckNile.json
It used to mean “Yet Another Markup Language” but was backronymed to clarify its focus as data-oriented.
YAML = “YAML Ain’t Markup Language”
Summary
Don’t
abstract
Be
functional
Isolate side
effects
Use a backup
service
Use consistent
formatting
Use an outside
product to control
lifecycle
For more information 43
F#
fsharp.org
fsharpforfunandprofit.com
Event sourcing
http://www.infoq.com/news/2014/09/greg-young-event-sourcing
https://www.youtube.com/watch?v=JHGkaShoyNs
Microservices
martinfowler.com
microservices.io
Rachel Reese Jet.com
@rachelreese @JetTechnology
Patterns and Practices for
Real-world Event-driven
Microservices

Weitere ähnliche Inhalte

Was ist angesagt?

How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...
How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...
How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...
Adriano Raiano
 

Was ist angesagt? (20)

Fast C++ Web Servers
Fast C++ Web ServersFast C++ Web Servers
Fast C++ Web Servers
 
Take Flight - Using Fly with the Play Framework
Take Flight - Using Fly with the Play FrameworkTake Flight - Using Fly with the Play Framework
Take Flight - Using Fly with the Play Framework
 
Serverless Architecture - A Gentle Overview
Serverless Architecture - A Gentle OverviewServerless Architecture - A Gentle Overview
Serverless Architecture - A Gentle Overview
 
KNATIVE - DEPLOY, AND MANAGE MODERN CONTAINER-BASED SERVERLESS WORKLOADS
KNATIVE - DEPLOY, AND MANAGE MODERN CONTAINER-BASED SERVERLESS WORKLOADSKNATIVE - DEPLOY, AND MANAGE MODERN CONTAINER-BASED SERVERLESS WORKLOADS
KNATIVE - DEPLOY, AND MANAGE MODERN CONTAINER-BASED SERVERLESS WORKLOADS
 
Serverless Architecture Patterns - Manoj Ganapathi
Serverless Architecture Patterns - Manoj GanapathiServerless Architecture Patterns - Manoj Ganapathi
Serverless Architecture Patterns - Manoj Ganapathi
 
Chatbots with Serverless
Chatbots with ServerlessChatbots with Serverless
Chatbots with Serverless
 
Meetup Melbourne August 2017 - Agile Integration with Apache Camel microservi...
Meetup Melbourne August 2017 - Agile Integration with Apache Camel microservi...Meetup Melbourne August 2017 - Agile Integration with Apache Camel microservi...
Meetup Melbourne August 2017 - Agile Integration with Apache Camel microservi...
 
JavaDay Lviv: Serverless Archtiectures
JavaDay Lviv: Serverless ArchtiecturesJavaDay Lviv: Serverless Archtiectures
JavaDay Lviv: Serverless Archtiectures
 
AWS Lambda from the trenches
AWS Lambda from the trenchesAWS Lambda from the trenches
AWS Lambda from the trenches
 
Building a Serverless Pipeline
Building a Serverless PipelineBuilding a Serverless Pipeline
Building a Serverless Pipeline
 
Squeezing Machine Learning into Serverless for Image Recognition - AWS Meetup...
Squeezing Machine Learning into Serverless for Image Recognition - AWS Meetup...Squeezing Machine Learning into Serverless for Image Recognition - AWS Meetup...
Squeezing Machine Learning into Serverless for Image Recognition - AWS Meetup...
 
Hello elixir (and otp)
Hello elixir (and otp)Hello elixir (and otp)
Hello elixir (and otp)
 
How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...
How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...
How dorma+kaba leverages and deploys on CloudFoundry - CloudFoundry Summit Eu...
 
Continuous Delivery to Amazon ECS
Continuous Delivery to Amazon ECSContinuous Delivery to Amazon ECS
Continuous Delivery to Amazon ECS
 
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
 
locize tech talk
locize tech talklocize tech talk
locize tech talk
 
ApacheCon NA - Apache Camel K: a cloud-native integration platform
ApacheCon NA - Apache Camel K: a cloud-native integration platformApacheCon NA - Apache Camel K: a cloud-native integration platform
ApacheCon NA - Apache Camel K: a cloud-native integration platform
 
AWS December 2015 Webinar Series - Continuous Delivery to Amazon EC2 Containe...
AWS December 2015 Webinar Series - Continuous Delivery to Amazon EC2 Containe...AWS December 2015 Webinar Series - Continuous Delivery to Amazon EC2 Containe...
AWS December 2015 Webinar Series - Continuous Delivery to Amazon EC2 Containe...
 
Managing AWS infrastructure using CloudFormation
Managing AWS infrastructure using CloudFormationManaging AWS infrastructure using CloudFormation
Managing AWS infrastructure using CloudFormation
 
AWS meets Continuous Delivery
AWS meets Continuous DeliveryAWS meets Continuous Delivery
AWS meets Continuous Delivery
 

Andere mochten auch

DDD-Enabling Architectures with EventStore
DDD-Enabling Architectures with EventStoreDDD-Enabling Architectures with EventStore
DDD-Enabling Architectures with EventStore
SzymonPobiega
 
An Introduction to Reactive Application, Reactive Streams, and options for JVM
An Introduction to Reactive Application, Reactive Streams, and options for JVMAn Introduction to Reactive Application, Reactive Streams, and options for JVM
An Introduction to Reactive Application, Reactive Streams, and options for JVM
Steve Pember
 
Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features
WSO2
 
UML, OWL and REA based enterprise business model 20110201a
UML, OWL and REA based enterprise business model 20110201aUML, OWL and REA based enterprise business model 20110201a
UML, OWL and REA based enterprise business model 20110201a
Richard Kuo
 
Parallel Complex Event Processing
Parallel Complex Event ProcessingParallel Complex Event Processing
Parallel Complex Event Processing
Karol Grzegorczyk
 

Andere mochten auch (20)

How to build an event-driven, polyglot serverless microservices framework on ...
How to build an event-driven, polyglot serverless microservices framework on ...How to build an event-driven, polyglot serverless microservices framework on ...
How to build an event-driven, polyglot serverless microservices framework on ...
 
DDD-Enabling Architectures with EventStore
DDD-Enabling Architectures with EventStoreDDD-Enabling Architectures with EventStore
DDD-Enabling Architectures with EventStore
 
EventStore as a message broker
EventStore as a message brokerEventStore as a message broker
EventStore as a message broker
 
Real World Event Sourcing and CQRS
Real World Event Sourcing and CQRSReal World Event Sourcing and CQRS
Real World Event Sourcing and CQRS
 
autodiscoverable microservices with vertx3
autodiscoverable microservices with vertx3autodiscoverable microservices with vertx3
autodiscoverable microservices with vertx3
 
An Introduction to Reactive Application, Reactive Streams, and options for JVM
An Introduction to Reactive Application, Reactive Streams, and options for JVMAn Introduction to Reactive Application, Reactive Streams, and options for JVM
An Introduction to Reactive Application, Reactive Streams, and options for JVM
 
Standards Based Approach to User Interface Development
Standards Based Approach to User Interface DevelopmentStandards Based Approach to User Interface Development
Standards Based Approach to User Interface Development
 
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
WSO2 Product Release Webinar: WSO2 Complex Event Processor 4.0
 
Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features
 
WSO2 Complex Event Processor
WSO2 Complex Event ProcessorWSO2 Complex Event Processor
WSO2 Complex Event Processor
 
Reactive Microservices with Vert.x
Reactive Microservices with Vert.xReactive Microservices with Vert.x
Reactive Microservices with Vert.x
 
UML, OWL and REA based enterprise business model 20110201a
UML, OWL and REA based enterprise business model 20110201aUML, OWL and REA based enterprise business model 20110201a
UML, OWL and REA based enterprise business model 20110201a
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
C* Summit 2013: Eventual Consistency != Hopeful Consistency by Christos Kalan...
C* Summit 2013: Eventual Consistency != Hopeful Consistency by Christos Kalan...C* Summit 2013: Eventual Consistency != Hopeful Consistency by Christos Kalan...
C* Summit 2013: Eventual Consistency != Hopeful Consistency by Christos Kalan...
 
09 semantic web & ontologies
09 semantic web & ontologies09 semantic web & ontologies
09 semantic web & ontologies
 
Modern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.xModern app programming with RxJava and Eclipse Vert.x
Modern app programming with RxJava and Eclipse Vert.x
 
Parallel Complex Event Processing
Parallel Complex Event ProcessingParallel Complex Event Processing
Parallel Complex Event Processing
 
Event Driven Architecture (EDA), November 2, 2006
Event Driven Architecture (EDA), November 2, 2006Event Driven Architecture (EDA), November 2, 2006
Event Driven Architecture (EDA), November 2, 2006
 
Aaai 2011 event processing tutorial
Aaai 2011 event processing tutorialAaai 2011 event processing tutorial
Aaai 2011 event processing tutorial
 
DataStax: Rigorous Cassandra Data Modeling for the Relational Data Architect
DataStax: Rigorous Cassandra Data Modeling for the Relational Data ArchitectDataStax: Rigorous Cassandra Data Modeling for the Relational Data Architect
DataStax: Rigorous Cassandra Data Modeling for the Relational Data Architect
 

Ähnlich wie Patterns and practices for real-world event-driven microservices

Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukFlowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Elixir Club
 

Ähnlich wie Patterns and practices for real-world event-driven microservices (20)

Patterns & Practices for Cloud-based Microservices
Patterns & Practices for Cloud-based MicroservicesPatterns & Practices for Cloud-based Microservices
Patterns & Practices for Cloud-based Microservices
 
Chaos Testing with F# and Azure by Rachel Reese at Codemotion Dubai
Chaos Testing with F# and Azure by Rachel Reese at Codemotion DubaiChaos Testing with F# and Azure by Rachel Reese at Codemotion Dubai
Chaos Testing with F# and Azure by Rachel Reese at Codemotion Dubai
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
 
Advanced Model Inferencing leveraging Kubeflow Serving, KNative and Istio
Advanced Model Inferencing leveraging Kubeflow Serving, KNative and IstioAdvanced Model Inferencing leveraging Kubeflow Serving, KNative and Istio
Advanced Model Inferencing leveraging Kubeflow Serving, KNative and Istio
 
Sessionizing Uber Trips in Realtime - Flink Forward '18, Berlin
Sessionizing Uber Trips in Realtime  - Flink Forward '18, BerlinSessionizing Uber Trips in Realtime  - Flink Forward '18, Berlin
Sessionizing Uber Trips in Realtime - Flink Forward '18, Berlin
 
Serverless in-action
Serverless in-actionServerless in-action
Serverless in-action
 
Flink Forward Berlin 2018: Amey Chaugule - "Threading Needles in a Haystack: ...
Flink Forward Berlin 2018: Amey Chaugule - "Threading Needles in a Haystack: ...Flink Forward Berlin 2018: Amey Chaugule - "Threading Needles in a Haystack: ...
Flink Forward Berlin 2018: Amey Chaugule - "Threading Needles in a Haystack: ...
 
Building Event Driven (Micro)services with Apache Kafka
Building Event Driven (Micro)services with Apache KafkaBuilding Event Driven (Micro)services with Apache Kafka
Building Event Driven (Micro)services with Apache Kafka
 
Architecting Microservices in .Net
Architecting Microservices in .NetArchitecting Microservices in .Net
Architecting Microservices in .Net
 
Serverless GraphQL. AppSync 101
Serverless GraphQL. AppSync 101Serverless GraphQL. AppSync 101
Serverless GraphQL. AppSync 101
 
Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.
 
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukFlowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
 
AWS Step Functions을 활용한 서버리스 앱 오케스트레이션
AWS Step Functions을 활용한 서버리스 앱 오케스트레이션AWS Step Functions을 활용한 서버리스 앱 오케스트레이션
AWS Step Functions을 활용한 서버리스 앱 오케스트레이션
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
OpenDaylight and YANG
OpenDaylight and YANGOpenDaylight and YANG
OpenDaylight and YANG
 
How to be like amazon
How to be like amazonHow to be like amazon
How to be like amazon
 
How LEGO.com Accelerates With Serverless
How LEGO.com Accelerates With ServerlessHow LEGO.com Accelerates With Serverless
How LEGO.com Accelerates With Serverless
 
Azure tales: a real world CQRS and ES Deep Dive - Andrea Saltarello
Azure tales: a real world CQRS and ES Deep Dive - Andrea SaltarelloAzure tales: a real world CQRS and ES Deep Dive - Andrea Saltarello
Azure tales: a real world CQRS and ES Deep Dive - Andrea Saltarello
 
アドテク×Scala @Dynalyst
アドテク×Scala @Dynalystアドテク×Scala @Dynalyst
アドテク×Scala @Dynalyst
 
MCE^3 - Kyle Fuller - End-to-end Building Web Services in-swift-mce-2016
MCE^3 - Kyle Fuller - End-to-end Building Web Services in-swift-mce-2016MCE^3 - Kyle Fuller - End-to-end Building Web Services in-swift-mce-2016
MCE^3 - Kyle Fuller - End-to-end Building Web Services in-swift-mce-2016
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Patterns and practices for real-world event-driven microservices

  • 1. Rachel Reese Jet.com @rachelreese @JetTechnology Patterns and Practices for Real-world Event-driven Microservices
  • 3. We plan to be the new Amazon.com Launched July 22, 2015 • Both Apple & Android named our app as one of their top 5 for 2015 • Over 20k orders per day • Over 10.5 million SKUs • #4 marketplace worldwide • 700 microservices We’re hiring! http://jet.com/about-us/working-at-jet
  • 4. Azure Web sites Cloud services VMs Service bus queues Services bus topics Blob storage Table storage Queues Hadoop DNS Active directory SQL Azure R F# Paket FSharp.Data Chessie Unquote SQLProvider Python Deedle FAK E FSharp.Async React Node Angular SAS Storm Elastic Search Xamarin Microservices Consul Kafka PDW Splunk Redis SQL Puppet Jenkins Apache Hive EventStore
  • 6. Microservices An application of the single responsibility principle at the service level. Has an input, produces an output. Easy scalability Independent releasability More even distribution of complexity Benefits “A class should have one, and only one, reason to change.”
  • 8. Event-driven The focus of your application code is to react to events (single or a stream).
  • 9. Events Any significant change in state that has happened in your domain • Past tense • Immutable • Contains only relevant data to transaction All events should be represented as verbs in the past tense such as CustomerRelocated, CargoShipped, or InventoryLossageRecorded. For those who speak French, it should be passé composé, they are things that have completed in the past. Greg Young
  • 10. Event Consumer “Events” as the notification messages Event channelEvent Emitter
  • 11. Microservice input should be treated as an Observable Events should be an Observable Event-driven is Reactive Does anyone here use Rx?
  • 13. Compare to relational model which captures only the latest state change. These sets are then related to each other. Event-sourced • Event-sourced is about how you model the domain. • An append-only sequence of events as data store. • Keep track of all state changes. • Can REPLAY these event streams.
  • 15. How did Jet decide on microservices?
  • 19. The F# solution offers us an order of magnitude increase in productivity and allows one developer to perform the work [of] a team of dedicated developers… Yan Cui Lead Server Engineer, Gamesys “ “ “
  • 20. Why F#? Expanded feature set
  • 21. Expanded feature set: Option types
  • 22. Why F#? Concise & powerful code
  • 23. Concise & powerful code public abstract class Transport{ } public abstract class Car : Transport { public string Make { get; private set; } public string Model { get; private set; } public Car (string make, string model) { this.Make = make; this.Model = model; } } public abstract class Bus : Transport { public int Route { get; private set; } public Bus (int route) { this.Route = route; } } public class Bicycle: Transport { public Bicycle() { } } type Transport = | Car of Make:string * Model:string | Bus of Route:int | Bicycle C# F# Trivial to pattern match on!
  • 25. Concise & powerful code public abstract class Transport{ } public abstract class Car : Transport { public string Make { get; private set; } public string Model { get; private set; } public Car (string make, string model) { this.Make = make; this.Model = model; } } public abstract class Bus : Transport { public int Route { get; private set; } public Bus (int route) { this.Route = route; } } public class Bicycle: Transport { public Bicycle() { } } type Transport = | Car of Make:string * Model:string | Bus of Route:int | Bicycle | Train of Line:int let getThereVia (transport:Transport) = match transport with | Car (make,model) -> ... | Bus route -> ... | Bicycle -> ... Warning FS0025: Incomplete pattern matches on this expression. For example, the value ’Train' may indicate a case not covered by the pattern(s) C# F#
  • 27.
  • 28. type Booking = | Basic of Plane | Combo of Combo | FullPack of Plane * Hotel * Car and Plane = {Outbound: DateTime; Return: DateTime; Destination: Country} and Combo = | ``With Hotel`` of Plane * Hotel | ``With Car`` of Plane * Car and Hotel = {Arrival: DateTime; Departure: DateTime; Location: Country} and Car = {From: DateTime; To: DateTime; Location: Country} and Country = {Name: String; ``ISO 3166-1``: char*char}
  • 29.
  • 32. F# way 33 type Year = int type [<Measure>] percent type Customer = Simple | Valuable | MostValuable type AccountStatus = | Registered of Customer * since:Year | Unregistered let customerDiscount = function | Simple -> 1<percent> | Valuable -> 3<percent> | MostValuable -> 5<percent> let yearsDiscount = function | years when years > 5 -> 5<percent> | years -> 1<percent> * years let accountDiscount = function | Registered (customer, years) -> customerDiscount customer, yearsDiscount years | Unregistered -> 0<percent>, 0<percent> let asPercent p = decimal p / 100m let reducePriceBy discount price = price - price * (asPercent discount) let calculateDiscountedPrice price account = let custDiscount, yrsDiscount = accountDiscount account price |> reducePriceBy custDiscount |> reducePriceBy yrsDiscount
  • 34. Be functional! Prefer immutability Avoid state changes, side effects, and mutable data Use data in  data out transformations Think about mapping inputs to outputs. Look at problems recursively Consider successively smaller chunks of the same problem Treat functions as unit of work Higher-order functions
  • 35. Don’t abstract This one magical service could write to ALL of the following: …badly. Event store Nservice Bus MSMQ 0MQ SQL Server
  • 36. Isolate side effects Submit order microservice Insert order to SQL microservice Send thank you email microservice Updates SQL Sends “Thank you for ordering” Email Updates SQL Sends “Thank you for ordering” Email
  • 37. Use a backup service to replay events Service 1 runs in production as normal Backup service 1 replays events until up-to-date. Switch over. Instantly live with changes! Also stage a copy of any aggregate/data store until stream has completed replaying!
  • 38. type Input = | Product of Product type Output = | ProductPriceNile of Product * decimal | ProductPriceCheckFailed of PriceCheckFailed let handle (input:Input) = async { return Some(ProductPriceNile({Sku="343434"; ProductId = 17; ProductDescription = "My amazing product"; CostPer=1.96M}, 3.96M)) } let interpret id output = match output with | Some (Output.ProductPriceNile (e, price)) -> async {()} // write to event store | Some (Output.ProductPriceCheckFailed e) -> async {()} // log failure | None -> async {{ }} // log failure let consume = EventStoreQueue.consume (decodeT Input.Product) handle interpret What do our services look like? Define inputs & outputs Define how input transforms to output Define what to do with output Read events, handle, & interpret
  • 39. Microservices should not control own lifecycle Execution runtime Deployment Configuration Restarting Versioning Scaling Availability Grouping by subsystem Scheduling Input-output static analysis Dashboard Think IoC!
  • 40. Torch YAML files torchVer: 2.0.0 subSystem: PriceCheck name: PriceCheck description: checks prices on nile ver: 0.0.1 autoStart: always compile: true ha: aa ##active-active. Could be ap for active-passive scriptPath: PriceCheckNilePriceCheckNile.fsx libPath: binrelease args: --jsonConfig=PriceCheckNile.json It used to mean “Yet Another Markup Language” but was backronymed to clarify its focus as data-oriented. YAML = “YAML Ain’t Markup Language”
  • 41. Summary Don’t abstract Be functional Isolate side effects Use a backup service Use consistent formatting Use an outside product to control lifecycle
  • 42. For more information 43 F# fsharp.org fsharpforfunandprofit.com Event sourcing http://www.infoq.com/news/2014/09/greg-young-event-sourcing https://www.youtube.com/watch?v=JHGkaShoyNs Microservices martinfowler.com microservices.io
  • 43. Rachel Reese Jet.com @rachelreese @JetTechnology Patterns and Practices for Real-world Event-driven Microservices

Hinweis der Redaktion

  1. 400-1000 microservices.
  2. Right tool for the job company. Chaos testing is the right tool. Azure: Storage Q for At-least-once Svc bus for At-most-once, transactions, persistence, order guarantee and Kafka for event distribution 5-7 mins
  3. More even distribution of complexity: easier to create & maintain services (very small amount of logic), harder to manage all services. Shift complexity from biz logic to infrastructure. Better than one giant monolithic solution with 25 projects!
  4. Before moving on, let’s define events. -“Event” refers to both the event itself, as well as the notification message that’s passed to the rest of the system.
  5. Considering events as notification messages. This is push-based notification..
  6. Reactive manifesto: Responsive Message-driven Resilient Elastic Microservice input should treated as an Observable and event-sourced.
  7. How many folks do event-sourcing now?
  8. Account history or ledger. Can replay and adjust if needed. – if need a ref number for all transactions now. CAN CREATE THIS Found a bug. Ran out of sockets. Updated SQL schema. Re-indexing Elasticsearch.
  9. Why microservices? F#: data in -> data out; inputs -> outputs. A function. A microservice = just a function that naturally maps to an f# script, with input/out via the network. Also, naming: Best practices = naming services after the function they perform. Bad: “sku service” , good: “import skus" No explicit meeting where we decided to do microservices, one day we just realized we had a bunch of microservices
  10. Pattern #1.
  11. Fewer bugs come from less code. Rewrote into prod in 6 weeks!!
  12. More features that I’ll talk about tomorrow.
  13. NullReferenceException can be obviated because of option types. Similar to nullable<int> but different because: Can be used on any type (strings, functions) When pattern matched on, forces you to consider None case Can use map, iter, etc. functions. Nestable: Option<Option<int>> is valid.
  14. Option type is a simple discriminated union. Both are idiomatic. C# version still lacks structural equality. Would need to override equality, comparison, AND GetHashCode. Also not proper immutability because private set is still mutable. -- there should be no setter, and the backing field should be readonly. Pattern matching is like a switch statement, but WAY more powerful.
  15. Option type is a simple discriminated union. Both are idiomatic. C# version still lacks structural equality (based on contents): that means overriding the equality implementation, the comparison implementation, AND GetHashCode. (generates a hash code from your object instance). Also not proper immutability because private set is still mutable. To get real immutability, there should be no setter, and the backing field should be readonly. Pattern matching is like a switch statement, but WAY more powerful.
  16. Paul's team. BA asked for "notes from meeting", was actual code.
  17. Look at the code a little closer
  18. An article came out on CodeProject very recently. https://twitter.com/Functional_S/status/709457140021399552
  19. 25 lines of code to 118 lines of code. Doesn’t even show tests. WTF WHY.
  20. 31 lines of code.
  21. Once inputs and outputs are defined, the service is just a series of transformations. Can compose or pipe the operations. Trivial to make concurrent, to scale. Will help Composing handlers and avoiding handler’s hell. Subscription and handlers should be defined as a series of functions, outside the Micro Service. Functional! Using Async.Seq OO Patterns: command pattern, visitor pattern are both just higher order functions. HO fns often can more easily express a complex work flow.
  22. (no slide, but) IDEMPOTENCY.
  23. Where you can’t avoid side effects, isolate them! Can’t replay this service easily if SQL schema changes or if you find a bug -- will resend all emails!
  24. Aggregate = row in SQL table with latest aggregated info. Eg. Order shipped. Keep staged version of aggregated info until stream has **completed** replaying. Otherwise, you’re writing events to table. Might turn on, then turn off an account. (again, isolate side effects) If we change the SQL schema. Just replay events into new schema. Keep a second service around. Spin that one up to replay. Then switch over to it and live instant new schema.
  25. Decode >> Handle >> interpret Allows one fun to be called to implement. Being functional allows composition here.
  26. Use Docker, Consul, etc. We rolled our own because: We can deploy a new build in 30s (instead of 15-20 minutes for a cloud service.) Scaling should include adding a new VM with assorted relevant services (automatically).
  27. Active/active — Traffic intended for the failed node is either passed onto an existing node or load balanced across the remaining nodes. This is usually only possible when the nodes use a homogeneous software configuration. Active/passive — Provides a fully redundant instance of each node, which is only brought online when its associated primary node fails.[1] This configuration typically requires the most extra hardware.
  28. Greg Young videos.