Adsd Slides Feb2017-1490880187992
Adsd Slides Feb2017-1490880187992
#ADSDcourse
www.UdiDahan.com
DISTRIBUTED SYSTEMS THEORY
SYSTEMS ARE NOT APPLICATIONS
▪ Solutions:
▪ Solution:
▪ Solution:
▪ Solution:
Consider how to pinpoint problems in production
Some logging is helpful, too much can be harmful
▪ Solution:
“Product”
Time
Estimate Architect
Too broad a range
Estimate accepted
Now it’s a requirement
Reprioritize requirements
New dates
Schedule accepted
#11. BUSINESS LOGIC CAN AND
SHOULD BE CENTRALIZED
▪ “First name must be less than 40 characters”
Enforce in the UI? BL? DB? Everywhere?
Services
Calculation
Validation
Entities
#11. BUSINESS LOGIC CAN AND
SHOULD BE CENTRALIZED
▪ Solution:
Logic will be physically distributed
Can still “centralize” in the development view
[more reading] 4+1 views of software architecture
https://github.com/Particular/Presentation.MultiDimensional
SUMMARY
▪ A measure of dependencies
▪ If X depends on Y,
there is coupling between them
▪ If X depends on Y then:
▪ X is efferently coupled to Y
▪ Y is afferently coupled to X
COUPLING – WHICH KIND IS WORSE?
A 5 0
B 0 5
C 2 2
D 0 0
HOW TO COUNT COUPLING?
X Y A B
Only one method call 3 methods,
2 properties
A B
DB
Service A Service B
Synchronous Call
Waiting Working
Return
Service
Service A B
?
Service
B
Service A Service B
MakeCustomerPreferred(id)
Customer GetCustomerInfo(id)
Calling thread is
waiting for the
result
Service A Service B
MakeCustomerPreferred(id)
YieldCustomerInfo(id)
Got data?
Got data?
Data ready
Got data?
Service A Service B
MakeCustomerPreferred(id)
▪ Avoid requests/commands
Bad: “SaveCustomerRequested”
Service 1 Service 2
A B Service X
C
D
Service Y
E
▪ AddCustomerMessage:
Sent by clients to one logical server
Multiple physical servers behind a load balancer
▪ OrderCancelledEventMessage:
Published by one logical server
Multiple physical servers can publish the same
Platform Temporal
Spatial
Afferent
Efferent
MESSAGING PATTERNS
WHY MESSAGING?
▪ Reduces coupling
Use JSON/XML + AMQP for platform coupling
Use asynchronous messaging for temporal coupling
MESSAGING, COUPLING, & AUTONOMY
Schema A Schema B
Service A Service B
Communications
Initiating Target
Service Service
Id
Sends, and
keeps on
working
Store and
Forward
adds resilience
MSMQ
Outgoing Incoming
Client
PERFORMANCE – RPC vs MESSAGING
Throughput
Messaging
RPC
Load
▪ With RPC, threads are allocated with load
With messaging, threads are independent
Difference due to synchronous blocking calls
▪ Memory, DB locks, held longer with RPC
STANDARD SERVICE INTERFACES
Customer Service
IMessage
where T : IMessage
IHandleMessages<T>
void Handle(T message);
REPRESENT METHODS AS MESSAGES
IMessage
Change_Address_Msg
Guid Id
Address A
Make_Preferred_Msg
Guid Id
Change_Credit_Msg
Guid Id
Credit C
HANDLING LOGIC SEPARATED
IHandleMessages<T>
void Handle(T message);
H1: IHandleMessages<Change_Address_Msg>
H2:IHandleMessages<Make_Preferred_Msg>
H3: IHandleMessages<Change_Credit_Msg>
MULTIPLE HANDLERS PER MESSAGE
H1: IHandleMessages<Change_Address_Msg>
H4: IHandleMessages<Change_Address_Msgv2>
[HTTP] $$ Order
Call 1 of 3
App Tx Call 2 of 3 DB
App pool
recycle
Rollback
Where’s the order!?
WHEN DATABASES ARE DOWN
[HTTP] $$ Order
Call 1 of 3
App Tx Call 2 of 3 DB
Exception
Write to log A B
Retry
Append exception info
to headers*
Message ID: 1
Message ID: 2
Message ID: 3
Related To: 1
Related To: 2
Audit
Connect outgoing messages to ID of
message being processed
VISUALIZING THE AUDIT STORE
CALLING WEB SERVICES
Rollback
$$ Order
A B C D
$$ Order
A B C D
[HTTP] Msg
Messaging
Invoke
Gateway DB
WS
RETURN ADDRESS PATTERN
Initiating Target
Service Service
Return Address
MSMQ
Outgoing Incoming
Client
Client
CORRELATED REQUEST/RESPONSE
Based on Return Address
Initiating Target
Service Service
Message ID
Some time in
Correlation ID the future
Initiating Target
Service Service
Subscriber Publisher
Subscribe
Publish
Publish
Publish
Publish
publisher subscriber
Subscribe
subscriber
subscriber
subscriber subscriber
publisher subscriber abcdefgh
abcdefgh
subscriber
abcdefgh
subscriber
subscriber abcdefgh
subscriber abcdefgh
DON’T FORGET CONSISTENCY
BOUNDARIES
Service A Service B
MakeCustomerPreferred(id)
subscriber
Sub3 LB subscriber
subscriber
TOPIC HIERARCHIES & POLYMORPHISM
Order Accepted
Order Billed
https://particular.net/blog/what-does-your-particular-system-look-like
SUMMARY
▪ Building blocks are simple
IMessage
IHandleMessages
Send, Reply, and Publish
Fielding 2000
WHAT IS AN “ARCHITECTURAL STYLE”?
In plain English:
What is and isn’t allowed in an architecture
App 6 App 3
App 5 App 4
BROKER CHARACTERISTICS
Source Sink
Bus
Sink Source
BUS TOPOLOGY
App App
Bus.dll Bus.dll
App App
Bus.dll Bus.dll
App App
Bus.dll Bus.dll
App App
Bus.dll Bus.dll
BUS CHARACTERISTICS
▪ Communication is distributed
No single point of failure
peoplesoft biztalk
NServiceBus
▪ Protocol Bridging
IP*Works
Ftp, SMTP, POP, SMS
LDAP, DNS, etc
▪ Business Logic
SUMMARY
Schema A Schema B
Service A Service B
Communications
WHAT IS A SERVICE?
Subscribe to Product
Subscribe to Customer Pricing Updated
Status Updated
Publish
Product Pricing Updated
Publish
Customer Customer Status Updated Marketing
Care Publish Order Accepted
SERVICE EVENT LIFECYCLES
Business processes remain within services
Cascading events give rise to enterprise processes
Inventory Price
Replenished Changed
Order Order
Shipped Received
Customer
Billed
WHICH SERVICE OWNS THIS PAGE?
WHICH SERVICE OWNS THIS PAGE?
None
SERVICE DEPLOYMENTS
Product Catalog
Pricing Server
Inventory
Cross Sell
TOP-TO-BOTTOM SERVICES
UI
API
BL
DAL
DB
DEMO
ASP.NET MVC CompositeUI
bit.ly/particular-microservices
HOW TO MAKE A GRID
HOW TO MAKE A GRID
ProductNameA ProductNameB ProductNameC ProductNameD
AuthorNameA AuthorNameB AuthorNameC AuthorNameD
cover cover cover cover
image image image image
A B C D
€ 20.00 € 20.00 € 20.00 € 20.00
View
http://mydomain.com/products/123 model
load related
products client-side message broker
View
http://mydomain.com/products/123 model
publish `RelatedProductsFound`
receive event
load related
products client-side message broker
View
http://mydomain.com/products/123 model
load related
products
<div class=“price”>$49.99</div>
Makes it bold, red, large
Component Component
from Service from Service
B C
ACROSS THE ENTERPRISE SERVICES
S1 S2 S3
MOBILE
BACK END
PORTAL
CONFIGURATION MANAGEMENT
an example
http://go.particular.net/octopus
http://go.particular.net/octopus-script
AMAZON.COM CHECKOUT WORKFLOW
WHICH SERVICE OWNS THIS FLOW?
WHICH SERVICE OWNS THIS FLOW?
None
WORKFLOW EVENT COMPOSITION
OrderReceived
CustomerBilled
OrderShipped
WORKFLOW EVENT COMPOSITION
SetOrderId = 022032ba-1337-43a5-90c9-d48b58742c7
WORKFLOW COMPOSITION
Shipping
Sales
Billing
Billing
Sales Shipping
PARENT VS CHILDREN
Orders table
Id ShippingId FinanceId Etc
123 1337 42 …
124 1338 43 …
VS
VS
IT/Ops
DataExporter
message handler
▪ Regular reports:
Find the pattern users are looking for in the report
Model constants as domain concerns
Implement as event-correlation & send email
Surgery Service
PatientId
Laboratory data
Allergies information
Medication
vs
Medication Allergies
Service Service
INSURANCE Home Insurance
Home owner
Travel
Insurance
Insured persons
Coverage Coverage
PolicyId PolicyId
ClaimId ClaimId
Automotive
Insurance
Insured vehicle
Coverage
PolicyId
ClaimId
vs
IT/Ops
Branding
▪ Make a booking
ONLINE #2.1
▪ Make a booking
Fill in guest info
Fill in credit card
ONLINE #2.2
▪ Check-in
Find booking
by last name
Verify info
Authorize $$
for full stay
Allocate room
FRONT DESK #4
▪ Check-out
Night before:
print out bill
Card is charged
amount authorized
BUSINESS & AUTONOMOUS
COMPONENTS
SERVICE DECOMPOSITION
Order 10 Products
Sales
Order 10 Million
Products
BUSINESS COMPONENTS
Sales
Order 10
Products
Regular
Customers
Order 10 Million
Strategic Products
Customers
MORE EXAMPLES
▪ Airlines
Different counters for business class customers
▪ Shipping
Need to track temperatures for frozen goods / meat
Can use regular trucks for toilet paper
▪ Billing
Monthly invoicing for customers with an agreement
Others billed directly to credit card
BUSINESS COMPONENTS & PUB/SUB
Fulfillment Billing
Regular
Products
Order Billed
Perishable
Products
TRANSACTIONS
Schema Message
Type
BACK END
PORTAL
AC’S , BC’S, AND SERVICES
Service
AC DB
AC BC
AC DB
AC BC
COUPLING BETWEEN ACS
Storage End
DB Point Msg
Order
Processing
Strategic
Customers
SUMMARY
▪ Autonomous Components are the unit of packaging
in SOA – deployed into Systems.
AC DB
AC BC
AC DB
AC BC
MULTI-USER COLLABORATION
Need to assume users are looking at stale data
User is
looking at Change
stale data data
HOW MUCH DATA IS COLLABORATIVE?
SIMPLEST SOLUTION? HARDLY.
UI
Facade
Cache
BL
DAL
DB
WHY TRANSFORM BETWEEN TIERS?
Keeping the cache up to date is even more work
Cache
UI
WS
DB
Map from DTOs &
WS to view model Map from DTOs
and WS to Use ORM to map
domain objects from tables to
domain objects
SIMPLER SOLUTIONS
▪ Datasets UI through to DB
▪ Ruby on Rails
Browser
IT/Ops
authentication JSON over HTTP
and authorization
can intercept
Document DB
FACETED SEARCH
Search:
Product A
watches Consectetur adipiscing elit. Etiam in
laoreet ante. Etiam rutrum neque nec
dui consequat, in pulvinar leo porttitor.
Brand Mauris congue, arcu et semper lacinia,.
FitBit Product B
Casio Consectetur adipiscing elit. Etiam in
laoreet ante. Etiam rutrum neque nec
dui consequat, in pulvinar leo porttitor.
Mauris congue, arcu et semper lacinia,.
Style
search results
Casual Product C
Consectetur adipiscing elit. Etiam in
Luxury laoreet ante. Etiam rutrum neque nec
dui consequat, in pulvinar leo porttitor.
Mauris congue, arcu et semper lacinia,.
Price
Product D
Under $25 Consectetur adipiscing elit. Etiam in
laoreet ante. Etiam rutrum neque nec
$25 to $100 dui consequat, in pulvinar leo porttitor.
Mauris congue, arcu et semper lacinia,.
RECOMMENDATION ENGINES
ProductNameA ProductNameB ProductNameC ProductNameD
AuthorNameA AuthorNameB AuthorNameC AuthorNameD
cover cover cover cover
image image image image
A B C D
€ 20.00 € 20.00 € 20.00 € 20.00
View
http://mydomain.com/products/123 model
load related
products client-side message broker
begin transaction
var quantity = select Quantity from Inventory
where Id = @ProdId
if (quantity >= quantityRequested)
update Inventory
set Quantity = quantity – quantityRequested
where Id = @ProdId
commit transaction
CONNECTION POOL DRIES UP
Business needs to get flexible
Negative inventory is OK
APPEND ONLY DATAMODELS
begin transaction
select @quantity = sum(Delta),
TimeStamp.Before(5.min.ago)
from Inventory where Id = @ProdId
delete from Inventory where Id = @ProdId
and TimeStamp.Before(5.min.ago)
insert into Inventory @ProdId, @quantity, now()
commit transaction
...OR ATOMIC INCREMENT
network
partition
+100
-1
-3
-4
-2
CQRS THEORY
?
QUERIES
BE UP FRONT ABOUT QUERY STALENESS
Your account
Balance correct as
of 10 minutes ago
KEEP QUERIES SIMPLE
2 Layers == 2 Tiers
UI
Query only
Rep_Customers_Table Supervisor_Customers_Table
DEPLOYMENT AND SECURITY
▪ Deploy the persistent view model DB to the web tier
(only SELECT is permitted)
Don’t have to go through the firewall – faster
▪ Role-based security
Different screens for different roles go to different
tables – SELECT permissions per role
▪ Uniqueness
Can expose to user (user signup)
DB
COMMAND PROCESSING TIERS
Transaction
Get
current
Command state
Input WS
Persist DB
Validation Validation
Rules
AMAZON.COM “ADD TO SHOPPING CART”
Item added
shown
(from cmd)
SHOULD WE DO WHAT THE USER ASKED?
Orders
ID Total Date Shipped Account etc etc etc
317 $37.87 1/9/09 Yes A17T5
318 $99.99 3/7/09 Yes A17T5
319 $100.11 4/8/09 Yes P313Z
320 $69.47 9/9/09 No P599Z
Save Cancel
RESERVATION SYSTEMS
RESERVATION SYSTEMS
UI BORN OF SINGLE USER THINKING
“Thank you.
Your confirmation email will arrive shortly”
OR
Just fake it in the UI
▪ Inherently asynchronous
▪ Not really related to an entity
COMMANDS VERSUS ENTITIES
▪ It’s easier to validate the command
Less data
More specific
Queries
View Model
Queries
View Model
Updater
Publish
Input WS
UI
Validation Rules
DB
Commands
SUMMARY
▪ Think of reads and writes differently
AC DB
AC BC
AC DB
AC BC
MONITORING QUEUE-BASED SYSTEMS
# of 1000 500
A B
messages
Total msg 2s 10 s
processing
time
Performance Counters
SO, WHICH IS WORSE?
A B
SLA SLA
100% 100%
80%
60%
T T
THE MOST IMPORTANT METRIC
B
SLA
100%
60%
Predicted time to
breach SLA
SCALABILITY
TX receive ACI
TX receive
Autonomous TX receive
Component
Instance
on each ACI ACI
machine
COMPETING CONSUMER 2: DISTRIBUTOR
Autonomous Component
Distributor ACI
Ready
Autonomous
Component
Instance
on each ACI ACI
machine
HETEROGENEOUS SERVER FARMS
Pull
Pull Pull
Pull
VIRTUALIZATION – PART 1
Client Server DB
V1 V1 V1 V1
V2
V2
V2 V2
Time
ZERO-DOWNTIME UPGRADES
Flexibility
Scalability
Monitoring
Versioning
LONG RUNNING PROCESSES
WHAT IS “PROCESS”?
System A B C
Request
Store
Response
LONG RUNNING PROCESS IMPLEMENTATION
Process Queue
Send requests to 3
Request other partners
Done!
Enqueue Response or publish event
SAGAS
Dispatch
Message Sag 3.Fill
Saga
Bus
a Persister
Complete
Saga Complete
Timeouts are
regular 1.Get Delete
Sagas msg
msg
Logic
WS
3rd party
WS
WORKFLOW & ORCHESTRATION
Here?
Here?
Here?
Here?
Here?
Here?
THE BOOK
that changed everything
Events
WHEN TO USE IT, WHEN NOT TO
UI DB
Communications
DOMAIN MODELS MADE OF “POJO”S
public class Product
public class Customer {
{ // properties
// properties // methods
// methods }
}
Call a
method
Check
properties &
event args
UNIT TEST SAMPLE
[TestMethod]
public void CreateOrderShouldConnectToCustomer()
{
Customer c = new Customer();
Order o = c.CreateOrder();
Assert.AreEqual(c, o.Customer);
}
CAN BE DEPLOYED MULTI-TIER
Different types of domain models for different tiers
SQL CLR
CONCURRENCY MODELS
Optimistic
Realistic
Pessimistic
MULTI-TABLE SPANNING TRANSACTIONS
Time TX 1 TX 2 TX 3
T2 Read B
T3 Commit Use values Commit
of A and B to
Update C
T4 Commit
Race condition
EVEN IF THEY’RE EASY TO IMPLEMENT
public class Order
{
public void Cancel()
{
if (status != OrderStatusEnum.Shipped)
//cancel
}
Rules:
1. Cannot cancel shipped orders Why?
Because shipping costs money So?
That money would be lost
if the customer cancelled Why?
▪
Yes
DIG DEEPER
What does a customer have to do
in order to get a refund?
CONSIDER SERVICE BOUNDARIES
N
Pref?
Y
Calc total val of orders Calc total val of orders
in past 2 weeks in past 1 week
DB
CSS
ALMOST THERE…
Cached by ISP
Dept.XML
Cached by CDN
Kindle.XML
Nobody
even comes
knocking
PERSONALIZATION