emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc. – Telegram
emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc.
3.48K subscribers
119 photos
15 videos
22 files
1.14K links
Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, Extreme Programming, SDLC, Agile, etc.

Chat: https://news.1rj.ru/str/emacsway_chat

Persistence: https://dckms.github.io/system-architecture/
Download Telegram
emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc.
Тут нужно сделать короткое отступление. Хотя, как говорилось ранее, "Хьюитт был против включения требований о том, что сообщения должны прибывать в том порядке, в котором они отправлены на модель актора", в современных реализациях Actor Model mailbox представлен…
Решение?

📝 "While not discussed in detail here, Message Metadata can be used to achieve causal consistency [AMC-Causal Consistency https://queue.acm.org/detail.cfm?id=2610533 ] among Messages (130) that must be replicated across a network with full ordering preserved [Bolt-on Causal Consistency http://www.bailis.org/papers/bolton-sigmod2013.pdf ]."
- "Reactive Messaging Patterns with the Actor Model: Applications and Integration in Scala and Akka" by Vaughn Vernon, Chapter "10. System Management and Infrastructure :: Message Metadata/History"

📝 "Even so, a technique called causal consistency [AMC-Causal Consistency https://queue.acm.org/detail.cfm?id=2610533 ] can be used to achieve the same."
- "Reactive Messaging Patterns with the Actor Model: Applications and Integration in Scala and Akka" by Vaughn Vernon, Chapter "10. System Management and Infrastructure :: Message Journal/Store"

📝 "To see the full power that results from using Domain Events , consider the concept of causal consistency. A business domain provides causal consistency if its operations that are causally related —one operation causes another—are seen by every dependent node of a distributed system in the same order [Causal https://queue.acm.org/detail.cfm?id=2610533 ] . This means that causally related operations must occur in a specific order, and thus one thing cannot happen unless another thing happens before it. Perhaps this means that one Aggregate cannot be created or modified until it is clear that a specific operation occurred to another
Aggregate."
- "Domain-Driven Design Distilled" by Vaughn Vernon

Посмотреть вживую обеспечение Causal Consistency на уровне подписчика можно в EventSourcing Framework:
- https://eventsourcing.readthedocs.io/en/v8.3.0/topics/process.html#causal-dependencies

Реализация:
- https://github.com/johnbywater/eventsourcing/blob/fd73c5dbd97c0ae759c59f7bb0700afb12db7532/eventsourcing/application/process.py#L273

Собственно, Causal является промежуточным уровнем строгости согласованности, чтобы избежать строгую линеаризацию сообщений (которая часто избыточна) из соображений сохранения параллелизма и повышения производительности, но при этом, не допускать параллелизма в потоках причинно-зависимых сообщений (где очередность сообщений, действительно, востребована).

Обычно идентификатором потока (streamId) выступает идентификатор агрегата. А идентификатором последовательности события в этом потоке (position) обычно выступает номер версии агрегата:
https://github.com/johnbywater/eventsourcing/blob/fd73c5dbd97c0ae759c59f7bb0700afb12db7532/eventsourcing/application/process.py#L82

#DDD #Microservices #DistributedSystems #EIP
emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc.
Решение? 📝 "While not discussed in detail here, Message Metadata can be used to achieve causal consistency [AMC-Causal Consistency https://queue.acm.org/detail.cfm?id=2610533 ] among Messages (130) that must be replicated across a network with full ordering…
📝 "Note that just saving the Domain Event in its causal order doesn’t guarantee that it will arrive at other distributed nodes in the same order. Thus, it is also the responsibility of the consuming Bounded Context to recognize proper causality. It might be the Domain Event type itself that can indicate causality, or it may be metadata associated with the Domain Event, such as a sequence or causal identifier. The sequence or causal identifier would indicate what caused this Domain Event, and if the cause was not yet seen, the consumer must wait to apply the newly arrived event until its cause arrives. In some cases it is possible to ignore latent Domain Events that have already been superseded by the actions associated with a later one; in this case causality has a dismissible impact [об этом способе уже говорилось ранее, прим. моё]."
- "Domain-Driven Design Distilled" by Vaughn Vernon, Chapter "6. Tactical Design with Domain Events:: Designing, Implementing, and Using Domain Events"

📝 "The first option is to use message sessions, a feature of the Azure Service Bus. If you use message sessions, this guarantees that messages within a session are delivered in the same order that they were sent.
The second alternative is to modify the handlers within the application to detect out-of-order messages through the use of sequence numbers or timestamps added to the messages when they are sent. If the receiving handler detects an out-of-order message, it rejects the message and puts it back onto the queue or topic to be processed later, after it has processed the messages that were sent before the rejected message."
- "CQRS Journey" by Dominic Betts, Julián Domínguez, Grigori Melnik, Fernando Simonazzi, Mani Subramanian, Chapter "Journey 6: Versioning Our System :: Message ordering"
https://docs.microsoft.com/ru-ru/previous-versions/msp-n-p/jj591565(v=pandp.10)#message-ordering

📝 "Actors must be prepared to accept and reject messages based on their current state, which is reflected by the order in which previous messages were received. Sometimes a latent message could be accepted even if it is not perfect timing, but the actor’s reaction to the latent message may have to carefully take into account its current state beforehand. This may be dealt with more gracefully by using the actors become() capabilities."
- "Reactive Messaging Patterns with the Actor Model: Applications and Integration in Scala and Akka" by Vaughn Vernon, Chapter "5. Messaging Channels :: Point-to-Point Channel"

#DDD #Microservices #DistributedSystems
emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc.
📝 "Note that just saving the Domain Event in its causal order doesn’t guarantee that it will arrive at other distributed nodes in the same order. Thus, it is also the responsibility of the consuming Bounded Context to recognize proper causality. It might be…
Родственные EIP patterns:
- "Correlation Identifier"
https://www.enterpriseintegrationpatterns.com/patterns/messaging/CorrelationIdentifier.html
- "Message Sequence"
https://www.enterpriseintegrationpatterns.com/patterns/messaging/MessageSequence.html

Применяется в том числе и в Event Sourcing.

В метаданных eventstore есть переменные $causationid and $correlationid.

📝 "The are both really simple patterns I have never quite understood why they end up so misunderstood.
Let's say every message has 3 ids. 1 is its id. Another is correlation the last it causation.
The rules are quite simple. If you are responding to a message, you copy its correlation id as your correlation id, its message id is your causation id.
This allows you to see an entire conversation (correlation id) or to see what causes what (causation id).
Cheers,
Greg Young"
https://discuss.eventstore.com/t/causation-or-correlation-id/828/4

Примеры:
- https://github.com/microsoftarchive/cqrs-journey/blob/6ffd9a8c8e865a9f8209552c52fa793fbd496d1f/noscripts/CreateDatabaseObjects.sql#L57-L62
- https://github.com/kgrzybek/modular-monolith-with-ddd/blob/4e2d66d16f97b3c863fbecd072dad52338516882/src/Modules/Payments/Infrastructure/AggregateStore/SqlStreamAggregateStore.cs#L44-L45

#DDD #Microservices #DistributedSystems #EIP
emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc.
Одной из непростых тем в DDD и микросервисной архитектуре является т.н. проблема "конкурирующих подписчиков". Это когда два причинно-зависимых события попадают на конкурирующие узлы обработки событий, и второе событие может "обогнать" первое, например, по…
Но даже если подписчик всего один, и сообщения доставляются последовательно, то и тогда очередность обработки сообщений может быть нарушена. Пример из NATS-Streaming Server:

📝 "With the redelivery feature, order can’t be guaranteed, since by definition server will resend messages that have not been acknowledged after a period of time. Suppose your consumer receives messages 1, 2 and 3, does not acknowledge 2. Then message 4 is produced, server sends this message to the consumer. The redelivery timer then kicks in and server will resend message 2. The consumer would see messages: 1, 2, 3, 4, 2, 5, etc...
In conclusion, the server does not offer this guarantee although it tries to redeliver messages first thing on startup. That being said, if the durable is stalled (number of outstanding messages >= MaxInflight), then the redelivery will also be stalled, and new messages will be allowed to be sent. When the consumer resumes acking messages, then it may receive redelivered and new messages interleaved (new messages will be in order though)."
- nats-streaming-server, issue #187 "Order of delivery", comment by Ivan Kozlovic
https://github.com/nats-io/nats-streaming-server/issues/187#issuecomment-257024506

#DDD #Microservices #DistributedSystems
emacsway-log: Software Design, Clean Architecture, DDD, Microservice Architecture, Distributed Systems, XP, Agile, etc.
Одной из непростых тем в DDD и микросервисной архитектуре является т.н. проблема "конкурирующих подписчиков". Это когда два причинно-зависимых события попадают на конкурирующие узлы обработки событий, и второе событие может "обогнать" первое, например, по…
Кстати, проблема очередности доставки сообщений хорошо описана в главе "Projections and Queries :: Building read models from events :: Subnoscriptions" книги "Hands-On Domain-Driven Design with .NET Core: Tackling complexity in the heart of software by putting DDD principles into practice" by Alexey Zimarev ( @zimareff )
https://www.amazon.com/Hands-Domain-Driven-Design-NET-ebook/dp/B07C5WSR9B

И он добавил несколько интересных аргументов в чат канала:
https://news.1rj.ru/str/emacsway_chat/85

P.S.: это один из тех людей, кому я искренне благодарен за влияние на мое профессиональное развитие.

#DDD #Microservices #DistributedSystems
Кстати, Яндекс-Переводчик знает толк в "Совершенстве" 🙂
Если вдруг кто пропустил эту новость - вышло второе издание бестселлера "The Pragmatic Programmer: your journey to mastery, 20th Anniversary Edition" (2nd Edition) by David Thomas: https://www.amazon.com/Pragmatic-Programmer-journey-mastery-Anniversary/dp/0135957052/

Автор - один из 17 подписантов Agile-manifesto и его соавтор.

Кстати, Dave тоже ударился в функциональное программирование, и написал книгу "Programming Elixir".

А так же он был редактором книги Джо Армстронга по Эрлангу:
"Dave Thomas edited my Erlang book"
https://web.archive.org/web/20170830231254/http://joearms.github.io/2013/05/31/a-week-with-elixir.html

#Agile #Career #FunctionalProgramming
📝 "A good architecture is characterized by crisp abstractions, a good separation of concerns, a clear distribution of responsibilities, and simplicity.
All else is details."

- Grady Booch. Позавчера.
https://twitter.com/Grady_Booch/status/1301810362119905285?s=19

[UPDATED]: Там весь тред заслуживает на прочтение.

#SoftwareDesign #SoftwareArchitecture
Немного дискуссионный, но весьма интересный материал от Vladimir Khorikov ( @vkhorikov ) на один из самых частых вопросов в DDD - может ли один агрегат иметь ассоциацию по ссылке с другим агрегатом?

"Link to an aggregate: reference or Id?"
https://enterprisecraftsmanship.com/posts/link-to-an-aggregate-reference-or-id/

#DDD #Microservices