Fundamental IDEALS And Domain Driven Design (DDD) For .

1y ago
17 Views
2 Downloads
3.11 MB
30 Pages
Last View : 30d ago
Last Download : 3m ago
Upload by : Troy Oden
Transcription

4/10/2020Fundamental IDEALS and DomainDriven Design (DDD) for designingmodern service-based systemsJoe Yoder – joe@refactory.comTwitter: @metayodahttps://refactory.comCopyright 2020 Joseph Yoder, The Refactory, Inc.SOLID is for OO designSingle responsibility principleOpen/closed principleLiskov substitution principleInterface segregation principleDependency inversion principle1

4/10/2020What if I’m designing servicesand microservices?Microservice styleThe microservice architectural style is an approach to developinga single application as a suite of small services, each running inits own process and communicating with lightweightmechanisms, often an HTTP resource API. These services are builtaround business capabilities and independently deployable byfully automated deployment machinery. 1The microservice style dictates that the deployment unitshould contain only one service or just a few cohesive servicesThis deployment constraint is the distinguishing factor21Lewis, J. & Fowler, M. “Microservices.” erson, P. “Defining Microservices.” SATURN blog, microservices.html2

4/10/2020Guiding IDEALS for microservicesInterface segregationDeployabilityEvent-drivenAvailability over consistencyLoose CouplingSingle responsibilityIDEALSInterface SegregationInterface Segregation Principle This principle deals with the disadvantages of “fat” interfaces [ ] The interfaces of the class can be broken up into groups of methods [ ] Each group serves a different set of clientsRobert C. Martin & Micah Martin. Agile Principles, Patterns, and Practices in C#.Prentice Hall, 2006.public Person createPerson(final String lastName,final String firstName,final String middleName,final String salutation,final String suffix,final String streetAddress,final String city,final String state,final chargender,final boolean isEmployed,final boolean isHomeOwner){ // implementation goes here }3

4/10/2020Interface Segregation for microservicesServices are often called by different types of clients, such as Web applications, mobile apps, other backend servicesTraditional SOA prescribed canonical schema: All clients should comply to the service contractToday: Each client should see a service contract that best suits its needsBut how?I knowhow BFFs!Backend for frontends (BFF) Variation of API gateway One API gateway for eachtype of client (frontend) Each API gateway doesrouting, transformations, etc.as needed by each client Each frontend team can beresponsible for their APIgateway4

4/10/2020IDEAL Microservices hugely increased the number of deployment units SDeployabilityGood design and implementationalone don’t warrant successAutomation is Key5

4/10/2020Event-Driven Synchronous request-response calls are still everywhereIDEALS But today’s scalability and performance requirements pose achallenge that calls for events processed asynchronouslyEvent-Driven Architecture (EDA)EDA is an architecture style in which componentscommunicate primarily through asynchronousmessages or events6

4/10/2020Event-driven exampleIDEALSAvailability over consistency The CAP theorem gives you two options: availability xor consistency We see enormous effort in industry to provide mechanisms to enableyou to choose availability, ergo embrace eventual consistency Why? Users won’t put up with lack of availability!Availability!Availability orconsistency?7

4/10/2020Availability over consistency in practice CQRS and Service Data ReplicationLoose couplingIDEALS High coupling has dependency between components or services These interdependencies and connections can makethe system harder to evolve and maintain8

4/10/2020Loose coupling for microservices Model around the business domain (DDD) Carefully design the contract Use wrapper patterns (adapter, façade, decorator, proxy) Use EDA, API Gateway, Asynchronous Messaging, Hypermedia, IDEALSIDEALSSingle responsibilitySingle Responsibility Principle: If a class has more than one responsibility, [they] become coupled [ ] This kind of coupling leads to fragile designs that break in unexpectedways when changed [ ]Subscription [SRP] is one of the simplest of the principles, statusbut one of the most difficult to get right paymentInfo activationDate expirationDate promotionCode renew() expire() convert() activate() inactivate()-applyDiscount() determineFee()Subscriptions: subscribe, status, promotions, payments9

4/10/2020Single responsibility for microservicesIf a microservice is packed with responsibilities,it might bear the pains of the monolithIf its responsibility is too slim several microservices might need to interact to fulfill a request data changes might be spread across different microservicesDistrubutedtransactioncadaver!DDD to the rescueDDD can help you define the size of your microservice Not the LOC size The size in terms of functional scopeLet’s look at how to Model Microservices with DDDA well designedmicroservice shallhave a singleresponsibility10

4/10/2020Guiding IDEALS for microservicesInterface segregationDeployabilityEvent-drivenAvailability over consistencyLoose CouplingSingle responsibilityModeling Microservices with DDD11

4/10/2020MotivationHow do I model my microservicesWhat is a good size of a microservicesHow do I avoid coupling problemsHow do I deal with distributed data and transactionsDomain-Driven Design (DDD)DDD is an approach to domain modeling created by Eric EvansDDD is not an approach to microservice designBut DDD can help with some aspects of microservice design20032013201512

4/10/2020Agile Approaches encourage Domain ExpertsVariation with a Shared Mental ing-made-functional201813

4/10/2020DDD main conceptsDomain Core domainAggregate Entity, value object, aggregate rootBounded context Context map, Anticorruption LayerUbiquitous languageApplication service, domain serviceRepositoryDomain eventDomainDomain is the problem to be solved with software in an organizationIt includes the concepts and business rules needed to achievethe business goals of the organizationExamples of organizations and their domains: DHL: shipping parcels Supreme Court: judicial cases involving the Constitution or federal law Angelo’s Pizza: produce and sell pizza14

4/10/2020Core domainDomain is the generic termA domain is typically composed of subdomainsA domain can be a core domain—is crucial for the success of the organization supporting subdomain—models important aspects of the businessthat are not core to the business generic subdomain—required by the business in an auxiliary fashionThe classification terms are not important;identifying core domains is important15

4/10/2020Domain modelTraffic Ticket DomainEach domain and subdomainhas its domain modelVehicleRegistrationServiceDriver ServiceViolationServicesEntityEntities have an ID and a life cycle, focus ison behavior, not data (rich object model)Examples: Driver, Customer, Order, PaymentValue ObjectValue objects represent characteristics or values in an entityExamples: Address, Amount, Distance, Price, Geolocation16

4/10/2020Example of Entity using @Entity JPAannotation (ORM mapping details omitted)@Entityclass TicketType(var id: Long,var description: String,var severity: Severity,var points: Int) {enum class Severity { CITYVIOLATION, CIVILINFRACTION,TRAFFICMISDEMEANOR }}@Embeddableclass LocationVO(var location: String,var municipalityId: Long}Example of VO using@Embeddable JPA annotationNote that a VO may holda reference to an entityAggregate An aggregate represents a cohesive businessconcept, such as Vehicle, Driver, Ticket, An aggregate has one or more entitieswith possible value objects One entity is the aggregate root The typical aggregate has one entityand a few VOs, but aggregates with2-3 entities are commonExternal objects/functions only see theaggregate through the aggregate root17

4/10/2020Aggregate transactional consistency An aggregate defines a (transactional) consistency boundary It remains transactionally consistent throughout its lifetime It is often loaded in its entirety from the database If an aggregate is deleted, all of its objects are deletedA database transaction shouldtouch only one aggregateInter-aggregate references Aggregate A may reference aggregate B The reference must use the ID of aggregate BDDD way @Entityclass TrafficTicket(var id: Long,var dateTime: Date,var location: LocationVO,var vehicleId: Long,var ticketTypeId: Long) {var driverId: Long? nullvar notes: String? null}Traditional OO way@Entityclass TrafficTicket(var id: Long,var dateTime: Date,var location: LocationVO,var vehicle: Vehicle,var ticketType: TicketType) {var driver: Driver? nullvar notes: String? null}18

4/10/2020Bounded ContextA bounded context (BC) delimits the scope of a domain modelBounded ContextA bounded context (BC) delimits the scope of a domain modelThe scope of a BC can be The entire domain model of a subdomain (recommended) Domain models of 2 subdomains (often happens with legacy systems) Part of the domain model of a subdomain (when we won’t implementthe other part)In practice The scope of a BC is often the scope of a traditional application system BCs are autonomous and a developer should be able to tell whether aconcept is in or out of a BC19

4/10/2020Ubiquitous language in a nutshell Ubiquitous Language is the term Eric Evans uses in Domain DrivenDesign for the practice of building up a common, rigorous languagebetween developers and domain experts. This language should bebased on the Domain Model used in the software - hence the needfor it to be rigorous, since software doesn't cope well with ambiguity.BusinessDomain JargonTechnicalJargonDomain experts should object to terms or structuresthat are awkward or inadequate to convey domainunderstanding; developers should watch forambiguity or inconsistency that will trip up design.-- Eric EvansDomain EventsA domain event is something of interest that has happened to an aggregateshould be expressed in past tensetypically represents state changeshould be represented by a class in the domain modelmay be organized in an event class hierarchyExamples: Traffic Ticket IssuedTraffic Ticket PaidDriver CreatedDriver’s License Suspended20

4/10/2020What’s the right size of a microservice?If it’s too large, it might bear the challenges of a monolithIf it’s too small: Several microservices might need to interact to fulfill a request Data changes might be spread across different microservices Distributed transactions might be neededDDD can help you define the size of your microservice Not the LOC size The size in terms of functional scopeBefore we discuss how we need tounderstand what is a microserviceWhat is a microservice in practice? Let’s build an example with a REST (http) backend serviceThis serviceexposes ss TrafficTicketController(val applicationService: TrafficTicketService) {@PostMapping("/traffic-ticket")fun createTicket(@RequestBody trafficTicketDto: TrafficTicketDto, response: HttpServletResponse):ResponseEntity TrafficTicketDto? {val newTrafficTicketDto applicationService.create(trafficTicketDto)return ResponseEntity(newTrafficTicketDto, fun updateTicket(@RequestBody trafficTicketDto: TrafficTicketDto):ResponseEntity TrafficTicketDto? {// . . .}The @RestController typically calls the DDD application service21

s VehicleController(val applicationService: VehicleService) {@PostMapping("/vehicle")fun createVehicle(@RequestBody vehicleDto: VehicleDto, response: HttpServletResponse):ResponseEntity VehicleDto? {val newVehicleDto applicationService.create(vehicleDto)return ResponseEntity(newVehicleDto, ")fun getVehicleByLicensePlate(. . .) TrafficTicketController and VehicleController are both REST services But are they microservices?If both services are part of the samedeployment unit, then it’s one microserviceThe deployment unit in thiscase is a docker image22

4/10/2020Scenarios for microservicescope and interactionFor operations handledentirely within the BC1.2.3.4.5.One-aggregate BC, one service, one microserviceA few aggregates in the BC, a few services, one microserviceTwo BCs, two microservices, they interact via eventsTwo BCs, two microservices, they interact via API calls with ACLTwo BCs, two microservices, they interact via data replicationFor operationsthat require interBC interactionNotation used in diagramsshowing microservices23

4/10/2020DDD and microservice scope (1)DDD can help define the microservice sizeScenario 1: a data changing operation affects a single aggregate One aggregate one service One service one microserviceDDD and microservice scope (2)Scenario 2: operation affects a few aggregates within the same BC Each aggregate one service A few aggregates one BC One BC one microserviceNo distributed transaction because services run in the same VM24

4/10/2020Putting it simplyA single service can be packaged as a microserviceBut a microservice may contain 2 services or 3 or even more, as long as they’re cohesiveDDD and microservice scope (3) Domain-level business logic spanning multiple aggregatescan be placed in a domain service The domain service interacts with different entities in the same BCSuggestion: create a@DomainService annotationthat is @Transactional25

4/10/2020Transactions over multiple BCsScenario 3: operation affects data in different BCs Each BC one microservice Use domain events for inter microservice communicationPublish-subscribe technologies can be used, such as KafkaRabbitMQVert.xAkkaEventuate TramEvent-based saga example (1)Local DBtransaction26

4/10/2020Event-based saga example (2)Event-based interaction – benefitsMaintainability Publishers and subscribers are independent and hence loosely coupled There’s more flexibility to add functionality by simply adding subscribers oreventsScalability and throughput Publishers are not blocked, and events can be consumed by multiplesubscribers in parallelAvailability and reliability: Temporary failures in one service are less likely to affect the others27

4/10/2020Event-based interaction – challenges (1)Maintainability The event-based programming model is more complex: Some of the processing happens in parallel and may require synchronizationpoints Correction events, and mechanisms to prevent lost messages may be needed Correlation identifiers may be neededTestability Testing and monitoring the overall solution is more difficultInteroperability and portability The event bus may be platform specific and cause vendor lock-inEvent-based interaction – challenges (2) Good UX is harder if end user needs to keep track of events We traded transactional consistency for eventual consistency28

4/10/2020Takeaways IDEALS are good design principles for designing microservices Domain Driven Design (DDD) can help with defining microservices DDD key concepts (for microservice design) are domain, subdomain,bounded context, aggregate, and entity A service (e.g., REST) can have the scope of an aggregate Model a microservice around the bounded context We can use domain events for inter-microservice (i.e., inter-BC) interactionTakeawaysWhether you use DDD or not,or you are creating microservcies or not:Traffic Ticket Domain Model around business capabilities or the domain Model the domain by using concepts such as: entities, aggregates,Subdomain: bounded context,Driver ubiquitous languageSubdomain:Veh & RegVehicle & nViolationService29

4/10/2020Guiding IDEALS for microservicesInterface segregationDeployabilityEvent-drivenAvailability over consistencyLoose CouplingSingle responsibilityJoseph Yoderhttps://refactory.comjoe@refactory.comTwitter @metayodaThanks to Paulo Merson30

Scenarios for microservice scope and interaction 1. One-aggregate BC, one service, one microservice 2. A few aggregates in the BC, a few services, one microservice 3. Two BCs, two microservices, they interact via events 4. Two BCs, two microservices, they interact via API calls with ACL 5. Two BCs, two microservices, they interact via data .

Related Documents:

Domain Cheat sheet Domain 1: Security and Risk Management Domain 2: Asset Security Domain 3: Security Architecture and Engineering Domain 4: Communication and Network Security Domain 5: Identity and Access Management (IAM) Domain 6: Security Assessment and Testing Domain 7: Security Operations Domain 8: Software Development Security About the exam:

An Active Directory domain contains all the data for the domain which is stored in the domain database (NTDS.dit) on all Domain Controllers in the domain. Compromise of one Domain Controller and/or the AD database file compromises the domain. The Active Directory forest is the security boundary, not the domain.

Domain Driven Design Domain-driven design (DDD) is an approach to the design of software, based on the two premises that complex domain designs should be based on a model, and that, for most software projects, the primary focus should be on the domain and domain logic (as opposed to being the particular technology used to implement the system).

time domain, we derive a nonintrusive data-driven model reduction technique that is based on the Loewner framework and that applies directly to time-domain formu-lations of, e.g., linear PDEs. Our time-domain Loewner approach is a data-driven nonintrusive model reduction technique that derives a reduced model from the time-

Eric Evans Domain-Driven Design : Introduction : What is Domain-Driven Design? 5 / 74. Domain Modelling DDD centres arounddomain modelling A diagram can represent and communicate the model, as can carefully written code, as can an English sentence

Prime Ideals and Maximal Ideals Definition (Prime Ideal, Maximal Ideal). A prime ideal A of a commuta-tive ring R is a proper ideal of R such that a,b 2 R and ab 2 A implies a 2 A or b 2 A. A maximal ideal A of R is a proper ideal of R if, whenever B is an ideal of R and A B R, then B A or B R.

In particular, Lemma 2.1 implies that ideals containing x2 i ¡xi xi(xi ¡1) in each variable (i.e., the boolean ideals) are radical. In Section 4, we will see that all ideals associated with dominating sets (and therefore Vizing’s conjecture) are radical for this reason. In general, it may be quite di–cult to determine a basis for p IJ.

Ideals and quotient rings 17 4. The monoid of ideals of R 20 5. Pushing and pulling ideals 21 . Boolean Algebras 189 3. Ideal Theory in Boolean Rings 192 4. The Stone Representation Theorem 194 . they had been making arguments about how algebraic varieties behave generically, but they lacked the technology to even give a precise meaning to .