Skip to content

Aggregates & Factories ​

"Cluster the entities and value objects into aggregates and define boundaries around each. Choose one entity to be the root of each aggregate, and allow external objects to hold references to the root only" — Eric Evans، Domain-Driven Design Reference (۲۰۱۵)، الگوی «Aggregates»

خلاصه (Summary): تجمیع (Aggregate) خوشهٔ کوچکی از entityها و value objectهاست با یک ریشه، یک مجموعه قاعدهٔ همیشه‌برقرار و یک تراکنش؛ هر چیزی بیرون از آن فقط با شناسه ارجاع داده می‌شود و «در نهایت» سازگار می‌شود، و کارخانه (Factory) راهی است که یک aggregate کامل و معتبر به دنیا می‌آید. تمرکز (Focus): aggregate و ریشه‌اش، invariantهای واقعی و مرز سازگاری، چهار قاعدهٔ Vernon (invariant واقعی، aggregate کوچک، ارجاع با شناسه، سازگاری نهایی بیرون از مرز) همراه با داستان شکستشان، آزمون «کار چه کسی است؟»، نشانه‌های اندازهٔ نادرست در هر دو جهت، همروندی خوش‌بینانه با version روی ریشه و تلاش دوباره، «یک aggregate در هر تراکنش» و چهار استثنایش، چرخهٔ عمر و شناسه، domain eventها و outbox، یک repository برای هر aggregate، factoryها (مستقل، factory method، بازسازی از ذخیره) در برابر سازنده و Eloquent factory، و نگاشت aggregate روی modular monolith و میکروسرویس. هدف یادگیری (Learning goal): با داشتن فهرست قواعد کسب‌وکار، مرز aggregate را طوری بکشید که فقط invariantهای واقعی را محافظت کند، ریشه را با ستون version، ثبت event و یک factory در Go و Laravel پیاده کنید، با تست ثابت کنید ویرایش هم‌زمان نمی‌تواند invariant را بشکند، و هر قاعدهٔ میان‌aggregateی (مثل «سفارش پرداخت‌نشده ارسال نمی‌شود») را روی eventها ببرید.

این فصل در گروه DD 02 (طراحی تاکتیکی) است. روی دو آجری که aggregate از آن‌ها ساخته می‌شود بنا شده، Entities & Value Objects، و روی خطی که دور یک مدل کشیده می‌شود، Bounded Context. پرسشی که این صفحه صاحبش است: مرز سازگاری درون یک context کجاست و نمونه‌هایش چطور ساخته می‌شوند؟ بقیه را همسایه‌ها می‌گویند: چرا رفتار باید روی ریشه باشد نه در سرویس‌ها (Anemic در برابر Rich)، aggregate چطور ذخیره و پیدا می‌شود (Repositories)، منطقی که در هیچ aggregateی جا نمی‌شود کجا می‌رود (سرویس‌های Domain، Application و Infrastructure)، و eventهای ریشه روی سیم چه می‌شوند (Domain Events در برابر Integration Events). سازوکار factory به‌عنوان الگوی GoF در الگوهای سازنده است؛ ستون version و FOR UPDATE به‌تفصیل در قفل خوش‌بینانه و بدبینانه؛ و ماشین‌آلات میان‌aggregateی در Saga و Outbox.

مثال جاری همانی است که در کل مسیر DDD می‌آید: یک کسب‌وکار سفارش آنلاین و ارسال با contextهای Sales، Fulfilment، Billing، Catalog و Identity. این‌جا aggregate Order را در Sales و aggregate Shipment را در Fulfilment طراحی می‌کنیم.

نقشهٔ صفحه (Page map) ​

دنبال چه هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
اصلاً چرا مرز سازگاریچرا aggregate وجود دارد
از Evans 2003 تا Vernon 2011، Helland، Dahan، Fowlerاز کجا آمده
خوشه، ریشه، نقطهٔ ورودAggregate و ریشه
invariant واقعی و ساختگی، قاعدهٔ ۱Invariantها و مرز سازگاری
چقدر بزرگ، رقابت، هزینهٔ بارگذاری، قاعدهٔ ۲Aggregate کوچک
شناسه به‌جای اشاره‌گر، lazy loading در Eloquent، قاعدهٔ ۳ارجاع با شناسه
«کار چه کسی است؟»، قاعدهٔ ۴سازگاری نهایی بیرون از مرز
چهار دلیل شکستن قاعدهیک aggregate در هر تراکنش
ستون version، تلاش دوباره، FOR UPDATEهمروندی روی ریشه
ساختن، شناسه، «حذف نکن»چرخهٔ عمر و شناسه
ریشه event ثبت می‌کند، outboxAggregate و domain event
یک repository برای هر aggregateAggregate و repository
factory مستقل، factory method، بازسازی، Eloquent factoryFactoryها
schema، الگوریتم ذخیره، کدهای خطا، رفتار هر محصولسازوکار
Order و Shipment کامل با تستGo، Laravel
Customer غول‌پیکر، aggregate به‌شکل جدول، setter عمومیحل مسئله‌های کلاسیک
کدام مرز برای کدام قاعدهانتخاب
از monolith تا دادهٔ توزیع‌شدهدر معماری
فقط آنچه لازم است بار کن، snapshot، read modelکارایی
تمرین عملیآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

واژه‌ها. هر سطر در فهرست مفاهیم باز می‌شود.

واژهبه زبان سادهمثال کوچکبدون آن چه خراب می‌شود
تجمیع (Aggregate)خوشه‌ای از اشیا که با هم بار، تغییر و ذخیره می‌شوندOrder با سطرهایشقاعده‌ها میان اشیای زیاد پخش می‌شوند و کسی پاسشان نمی‌دارد
ریشهٔ تجمیع (Aggregate root)تنها entityای که بیرونی‌ها حق لمسش را دارند؛ بقیه را پاس می‌داردOrder، نه OrderLineکدی مستقیم سطر را عوض می‌کند و «حداکثر ۲۰ سطر» می‌شکند
ناوردا (Invariant)قاعده‌ای که بعد از هر تراکنش باید درست باشدجمع کل = جمع سطرهاگزارش و فاکتور با هم نمی‌خوانند
مرز سازگاری (Consistency boundary)خطی که درونش invariantها فوراً برقرارندOrder + سطرها، نه Customerیا هیچ چیز محافظت نمی‌شود یا همه با هم قفل می‌شوند
ارجاع با شناسه (Reference by identity)نگه‌داشتن id یک aggregate دیگر، نه خود شیءcustomerId، skuبار کردن یک سفارش کل دیتابیس را بار می‌کند
سازگاری نهایی (Eventual consistency)aggregateهای دیگر کمی بعد، با event، هم‌پا می‌شوندShipment بعد از OrderPaid ساخته می‌شودتراکنش‌های غول‌پیکر یا به‌روزرسانی گم‌شده
نسخه (Version، قفل خوش‌بینانه)عددی روی ریشه که در هر ذخیره چک می‌شودWHERE id = ? AND version = 7دو کارمند بی‌صدا کار هم را رونویسی می‌کنند
کارخانه (Factory)کدی که یک aggregate کامل و معتبر سرهم می‌کندOrderFactory::fromCart()سفارش نیمه‌ساخته، invariantهایی که «بعداً» چک می‌شوند
بازسازی (Reconstitution)ساختن دوبارهٔ aggregate از ذخیره، بدون قاعده‌های ساخت و بدون eventOrder::reconstitute(...)بار کردن سفارش دوباره OrderPlaced شلیک می‌کند

چهار قاعدهٔ Vernon (هر کدام پایین‌تر یک بلوک دارد):

قاعدهبه زبان سادهشکست در صورت نادیده‌گرفتنکجا
Model true invariants in consistency boundariesفقط چیزی را داخل بگذار که باید اتمی با هم تغییر کندinvariantهای ساختگی: ویرایش‌های بی‌ربط با هم تداخل می‌کنندInvariantها
Design small aggregatesریشه به‌اضافهٔ چند value؛ entity فقط برای قاعدهٔ واقعیرقابت، بارگذاری کند، حافظهکوچک
Reference other aggregates by identityid نگه دار، هر وقت لازم شد جست‌وجو کنگراف‌های عمیق، نوشتن ناخواستهٔ چند aggregateبا شناسه
Use eventual consistency outside the boundaryقاعده‌های میان‌aggregateی بعداً، در تراکنش خودشان اجرا می‌شوندتراکنش‌های غول‌پیکر، قفل توزیع‌شدهنهایی

تراکنشی یا نهایی؟ (آزمون Vernon و Evans، جزئیات در سازگاری نهایی):

قاعده در فروشگاه مادرست‌کردنش کار کیست؟سازگاریسازوکار
سفارش حداکثر ۲۰ سطر داردخریداری که سفارش را ویرایش می‌کندتراکنشی، درون Orderریشه چک می‌کند؛ ستون version
جمع سفارش = جمع سطرهاخریدارتراکنشی، درون Orderمشتق‌شده، هرگز جدا ذخیره نمی‌شود
موجودی برای سفارش ثبت‌شده رزرو می‌شودسیستم (Inventory)نهاییOrderPlaced → گام saga → جبران
سفارش پرداخت‌نشده ارسال نمی‌شودسیستم (Billing، Fulfilment)نهاییShipment فقط از OrderPaid ساخته می‌شود
امتیاز وفاداری مشتری سفارش‌های پرداخت‌شده را نشان می‌دهدسیستمنهاییمصرف‌کنندهٔ OrderPaid
ارسال مرسوله سفارش را «ارسال‌شده» می‌کندسیستم (Fulfilment)نهاییParcelDispatched → Order.markDispatched()

چرا aggregate وجود دارد ​

مدل‌های دامنه پر از رابطه‌اند: سفارش سطر دارد، سطر به محصول اشاره می‌کند، سفارش مال یک مشتری است، مشتری آدرس، پرداخت و مرسوله دارد. اگر هر کسی بتواند هر شیئی را هر وقت خواست عوض کند، جایی نمی‌ماند که قاعده‌ای مثل «حداکثر ۲۰ سطر» را اعمال کند، و پرسش یک تراکنش دقیقاً چه چیزی را قفل می‌کند؟ بی‌جواب می‌ماند. Evans در DDD Reference مسئله را صاف می‌گوید: "It is difficult to guarantee the consistency of changes to objects in a model with complex associations." قفل بیشتر هم جواب نیست: "Cautious database locking schemes cause multiple users to interfere pointlessly with each other and can make a system unusable."

aggregate به هر دو پرسش با هم جواب می‌دهد. دور چند شیء خط می‌کشد، یکی را ریشه می‌نامد و می‌گوید: درون این خط، هر قاعده بعد از هر تراکنش برقرار است؛ بیرونش، هیچ قول فوری‌ای داده نمی‌شود.

aggregateهای کم و بزرگaggregateهای زیاد و کوچک
هر قاعده‌ای در یک تراکنش چک می‌شودفقط invariantهای واقعی در یک تراکنش چک می‌شوند
ویرایش‌های بی‌ربط تداخل می‌کنند (یک version برای همه چیز)ویرایش aggregateهای مختلف هرگز تداخل نمی‌کند
هزینهٔ بارگذاری با تاریخچه رشد می‌کندهزینهٔ بارگذاری از روی طراحی محدود است
نوشتنش آسان است، «کامل» به نظر می‌رسدevent، saga و UIای که «در انتظار» را بپذیرد لازم دارد
توزیع‌شدنی نیست: یک واحد، یک نودهر aggregate می‌تواند روی هر نود یا shard باشد
مناسب برای: ابزارهای کوچک تک‌کاربرهمناسب برای: هر چیزی با کاربران هم‌زمان یا رشد

تشبیهی که در این صفحه تکرار می‌کنیم: صورت‌حساب میز رستوران. گارسونی که میز شما دستش است صاحب صورت‌حساب شماست (ریشه). می‌توانید از او بخواهید دسر اضافه کند؛ نمی‌توانید به آشپزخانه بروید و روی برگهٔ آشپزخانه چیزی بنویسید (بخش درونی). صورت‌حساب قاعده دارد: یک واحد پول، جمعی که با اقلام برابر است، و هیچ قلمی بعد از پرداخت. آشپزخانه (Fulfilment) یک رونوشت از سفارش می‌گیرد و با برنامهٔ خودش کار می‌کند؛ پایانهٔ پرداخت (Billing) میز دیگری است. هیچ‌کس برای پرداخت یک صورت‌حساب کل رستوران را قفل نمی‌کند، و هیچ‌کس انتظار ندارد آشپزخانه و صندوق تا هزارم ثانیه هم‌نظر باشند.

Order aggregate = one consistency boundaryOrder (aggregate root)id, customerId, statusversion (optimistic lock)OrderLineentity, localOrderLineentity, localOrderLineentity, localMoney (value)Status (value)Invariants, checked by the root in one transactionlines at most 20; quantity 1..50; one currencytotal = sum(lines); draft-placed-paid-dispatched onlyApplication serviceorder.addLine(...)OrderRepositoryload / save wholeOutside codeline.quantity = 500CustomerIDIdentity ctxSKUCatalog ctxids only, neverobject references

تصویر aggregate Order را نشان می‌دهد: یک ریشه که id، status و version را نگه می‌دارد؛ سطرها و valueها درون مرز خط‌چین؛ invariantهایی که ریشه اعمال می‌کند؛ کد بیرونی فقط می‌تواند ریشه را صدا بزند؛ aggregateهای دیگر فقط به‌صورت id دیده می‌شوند. فلش ضربدرخورده یعنی دست‌بردن مستقیم در یک سطر از بیرون.

سه بدفهمی رایج، از همین اول ​

  1. «aggregate یعنی گراف اشیا، هر چه بزرگ‌تر بهتر.» Vernon: "aggregates are chiefly about consistency boundaries and not driven by a desire to design object graphs." یک Customer که همهٔ سفارش‌ها را در خودش دارد شکست کلاسیک است (حل مسئله).
  2. «aggregate یعنی یک جدول (یا یک مدل Eloquent).» aggregate مفهومی دامنه‌ای است که ممکن است چند جدول را بپوشاند (orders، order_lines)؛ و یک مدل Eloquent برای هر جدول با attributeهای عمومی درست برعکس ریشه‌ای است که از بخش‌هایش پاسداری می‌کند.
  3. «همهٔ قواعد کسب‌وکار باید در یک تراکنش چک شوند.» فقط قواعدی که باید در هر commit درست باشند داخل می‌آیند. Evans: "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously."

از کجا آمده ​

Evans، ۲۰۰۳. کتاب Domain-Driven Design (Addison-Wesley) الگوهای Aggregate، Factory و Repository را به‌عنوان الگوهای چرخهٔ عمر در بخش دوم معرفی کرد. DDD Reference رایگان (۲۰۱۵) آن‌ها را کوتاه بازگو می‌کند و ما در همهٔ صفحه از آن نقل می‌کنیم. این متن مرز را هم به تراکنش و هم به توزیع گره می‌زند: "Use the same aggregate boundaries to govern transactions and distribution." و "Keep an aggregate together on one server. Allow different aggregates to be distributed among nodes."

Helland، ۲۰۰۷. مقالهٔ CIDR پت هلند، Life beyond Distributed Transactions: an Apostate's Opinion، از تجربهٔ مقیاس Amazon استدلال کرد که برنامه‌های مقیاس‌پذیر روی «entity»های یکتا کار می‌کنند و "Atomic Transactions Cannot Span Entities". Vernon بعدها دربارهٔ آن می‌نویسد: "What we call aggregate he calls entity."

Dahan، ۲۰۰۹. دو نوشتهٔ Udi Dahan، Don't Create Aggregate Roots (ژوئن ۲۰۰۹) و Don't Delete – Just Don't (سپتامبر ۲۰۰۹)، به چرخهٔ عمر نگاه کردند: entityها از یک وضعیت قبلی کسب‌وکار ساخته می‌شوند ("In any transition, the previous state is the aggregate root.") و به‌ندرت حذف می‌شوند ("Orders aren’t deleted – they’re cancelled.").

Vernon، ۲۰۱۱. مقالهٔ سه‌بخشی Vaughn Vernon، Effective Aggregate Design (dddcommunity.org)، چهار قاعدهٔ سرانگشتی این صفحه، آزمون «کار چه کسی است؟» (که آن را به گفت‌وگویی با Evans نسبت می‌دهد) و چهار دلیل شکستن قاعدهٔ یک‌aggregate‌در‌هر‌تراکنش را داد. خود مقاله می‌گوید "is based on his upcoming book"، یعنی Implementing Domain-Driven Design (۲۰۱۳) که این متن فصل Aggregates آن شد؛ ما از مقاله نقل می‌کنیم، نه از کتاب.

Fowler، ۲۰۱۳. مدخل bliki با نام DDD_Aggregate (۲۳ آوریل ۲۰۱۳) تعریف کوتاهی است که بیشتر آدم‌ها اول می‌بینند: "A DDD aggregate is a cluster of domain objects that can be treated as a single unit."

text
     Year   Source                                      What it added
1    2003   Evans, Domain-Driven Design                 Aggregate, root, factory, repository
2    2007   Helland, Life beyond Distributed Tx          Entities as the unit of scale; no atomic tx across them
3    2009   Dahan, Don't Create Aggregate Roots          Creation comes from a previous state (factory method)
4    2009   Dahan, Don't Delete - Just Don't             Lifecycle ends in a business status, not DELETE
5    2011   Vernon, Effective Aggregate Design I-III     Four rules, "whose job is it?", reasons to break rules
6    2013   Fowler, DDD_Aggregate bliki                  Load/save whole aggregates; tx never cross them
7    2015   Evans, DDD Reference                         Short pattern texts quoted on this page

فهرست مفاهیم ​

هر بلوک همین ترتیب را دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، یک timeline، سناریوی واقعی، جدول مقایسه، و راه درست.

Aggregate و aggregate root حیاتی ​

به زبان ساده: aggregate چند شیء است که همیشه با هم سفر می‌کنند: همه را با هم بار می‌کنید، از یک در (ریشه) تغییرشان می‌دهید و همه را در یک تراکنش ذخیره می‌کنید.

بدفهمی رایج: «هر کلاسی که مجموعهٔ فرزند دارد ریشهٔ aggregate است.» Fowler هشدار می‌دهد که aggregateها "are sometimes confused with collection classes"؛ و Dahan اضافه می‌کند: "Aggregate roots aren’t a structural property of the domain model." ریشه را چون از یک قاعده محافظت می‌کند انتخاب می‌کنیم، نه چون بالای یک درخت نشسته است.

تعریف: aggregate خوشه‌ای از entityها و value objectهاست با یک مرز و دقیقاً یک entity ریشه. اشیای بیرونی فقط می‌توانند به ریشه ارجاع نگه دارند ("references to internal members passed out for use within a single operation only"، Evans). ریشه شناسهٔ سراسری دارد؛ entityهای درونی فقط درون aggregate شناسه دارند. invariantها برای کل aggregate تعریف و به دست ریشه اعمال می‌شوند. Fowler: "Aggregates are the basic element of transfer of data storage - you request to load or save whole aggregates. Transactions should not cross aggregate boundaries."

مسئولیت‌های ریشه:

مسئولیتدر کد یعنی چهOrder ما
اعمال invariantهاهر فرمان پیش از تغییر وضعیت همهٔ قواعد را چک می‌کندaddLine وضعیت، واحد پول، تعداد و سقف سطرها را چک می‌کند
نمایش رفتار، نه دادهمتدهایی به زبان فراگیر؛ بدون setterplace()، markPaid()، cancel()
پنهان‌کردن درونیاتentityهای درونی برای تغییر در دسترس نیستندline در Go صادر نشده؛ OrderLine تغییرناپذیر در PHP
تنها نقطهٔ ورود بودنrepository، سرویس‌ها و aggregateهای دیگر فقط با ریشه حرف می‌زنندOrderLineRepository نداریم
صاحب توکن همروندییک version برای کل مرزستون version روی orders
ثبت آنچه رخ دادdomain eventها روی ریشه جمع می‌شوندOrderPlaced، OrderPaid، OrderCancelled
text
     Request: "add 2 mugs to order o-1"
1    App service: order = repo.get("o-1")             loads root + lines (the whole boundary)
2    order.addLine("mug", 2, price)                    root checks: draft? same currency? 1..50? at most 20 lines?
3    root merges into its own line list                no outside code touched a line
4    repo.save(order)                                  UPDATE orders ... WHERE version = 7; rewrite lines; COMMIT
     Wrong path: OrderLine::find(42)->update(['quantity' => 500])  -> no root, no rule, no version bump

سناریوی واقعی: سفارش فروشگاه اینترنتی و سطرهایش (مثال کلاسیک)؛ یک ویزیت درمانگاه و اقلام تجویزشده‌اش؛ یک playlist و جایگاه آهنگ‌هایش (مثال‌های Fowler)؛ یک درخواست انتقال بانکی با پایه‌هایش؛ نقشهٔ صندلی یک اجرا در سیستم بلیت‌فروشی.

راه درست: entityهای درونی را برای نوشتن دست‌نیافتنی کنید (در Go صادرنشده، در PHP value object تغییرناپذیر یا مجموعهٔ private)، به ریشه متدهایی بدهید که نیت را می‌گویند، و بگذارید repository فقط ریشه‌ها را بار و ذخیره کند. کد کامل در Go و Laravel است.

Invariantها و مرز سازگاری (قاعدهٔ ۱) حیاتی ​

به زبان ساده: اول قواعدی را فهرست کنید که باید در هر commit درست باشند؛ فقط اشیایی که این قواعد لمسشان می‌کنند داخل یک aggregate می‌روند.

بدفهمی رایج: «اگر کسب‌وکار می‌گوید محصول backlog item دارد، backlog itemها داخل محصول می‌روند.» تیم Vernon دقیقاً همین کار را کرد و قواعدی مثل "If a sprint has committed backlog items, we must not allow it to be removed from the system." ساخت. حکم او: aggregate بزرگ "was designed with false invariants in mind, not real business rules."

تعریف: "An invariant is a business rule that must always be consistent." (Vernon، بخش اول). مرز سازگاری "logically asserts that everything inside adheres to a specific set of business invariant rules no matter what operations are performed." پس "aggregate is synonymous with transactional consistency boundary." یک invariant واقعی (True invariant) قاعده‌ای است که نقضش، حتی برای یک ثانیه، خطای کسب‌وکار است. یک invariant ساختگی (False invariant) راحتی ساختاری است که لباس قاعده پوشیده.

text
     Large Product aggregate (false invariants), optimistic locking on Product
     Bill                                       Joe
1    load Product v1                            load Product v1
2    plan a backlog item; COMMIT -> v2
3                                               schedule a release; COMMIT -> fails: based on v1
     "Nothing about planning a new backlog item should logically interfere with scheduling a new release!" (Vernon)

سناریوی واقعی: در فروشگاه ما «حداکثر ۲۰ سطر» و «جمع = جمع سطرها» invariantهای واقعی Order هستند. «مشتری وجود دارد» نیست: سفارش یک customerId نگه می‌دارد و Identity ممکن است بعداً مشتری را غیرفعال کند. «موجودی هست» هم نیست: قاعدهٔ Inventory است و با saga به آن می‌رسیم. سفارش خریدی که در آن "the sum of all line items must not surpass the total" (مثال کتاب Evans، به خلاصهٔ Vernon) invariant واقعی دارد و سطرها را درون ریشه توجیه می‌کند.

چطور از هم جدایشان کنیم:

پرسشinvariant واقعیinvariant ساختگی
یک ثانیه نقض، خطای کسب‌وکار است؟بله (فاکتور با جمع غلط)نه (عدد «تعداد سفارش» کهنه روی صفحهٔ مشتری)
خبرگان می‌گویندش، یا برنامه‌نویس از نمودار کلاس درآورده؟خبرگان می‌گوینداز «دارد» در یک جمله درآمده
کار یک کاربر آن را درست می‌کند؟معمولاً بلهاغلب کاربر دیگر یا سیستم
اگر بعداً با event اعمال شود چه می‌شود؟باگ دیدنیتأخیر کوچکی که کسی نمی‌بیند

راه درست: پیش از کشیدن جعبه‌ها invariantها را بنویسید (هر کدام یک خط، به زبان فراگیر)، هر کدام را «همان تراکنش» یا «در نهایت» علامت بزنید و مرز را فقط دور گروه اول بکشید. در کد، هر فرمان همهٔ invariantها را پیش از تغییر وضعیت چک می‌کند تا فرمان ردشده aggregate را دست‌نخورده بگذارد (تست Go با نام TestInvariantsRejectBeforeChangingState دقیقاً همین را می‌سنجد).

Aggregate کوچک طراحی کنید (قاعدهٔ ۲) حیاتی ​

به زبان ساده: ریشه و چند valueای را که باید با آن تغییر کنند نگه دارید؛ بقیه aggregate خودشان می‌شوند.

بدفهمی رایج: «کوچک یعنی یک جدول برای هر aggregate، یا یک فیلد.» Vernon: "The extreme would be an aggregate with only its globally unique identity and one additional attribute, which is not what's being recommended"؛ اندازهٔ درست "the root entity and a minimal number of attributes and/or value-typed properties" است، و "The correct minimum is the ones necessary, and no more."

تعریف: aggregate کوچک ریشه، value objectها و فقط آن entityهای درونی را دارد که یک invariant واقعی می‌خواهد. Vernon از پروژهٔ Niclas Hedhman گزارش می‌دهد که تیمش "approximately 70% of all aggregates with just a root entity containing some value-typed properties" طراحی کرد و بقیه دو یا سه entity داشتند. اندازه دربارهٔ آنچه باید با هم بار و قفل شود است، نه تعداد خطوط کد.

text
     Too large: Order inside Customer (one version on Customer)
1    09:00:01  tab A: customer.changeAddress()        load Customer + 3,000 orders; COMMIT v41 -> v42
2    09:00:01  tab B: customer.placeOrder()           load the same graph; COMMIT based on v41 -> conflict
3    09:00:02  warehouse: customer.orders[17].dispatch()conflict again; retry storms at peak

     Too small: Order and OrderLine as separate aggregates (each with its own version)
1    T1 loads Order (19 lines counted by query)       T2 loads Order (19 lines)
2    T1 inserts OrderLine #20; COMMIT                 T2 inserts OrderLine #21; COMMIT
3    -> 21 lines: the invariant "at most 20" lives in no single boundary

سناریوی واقعی: نشانه‌های aggregate بزرگ: شکست‌های مکرر قفل خوش‌بینانه روی یک ریشهٔ داغ (ردیف Product که هر فروش لمسش می‌کند)، بارگذاری کند چون یک مجموعه با تاریخچه رشد می‌کند (همهٔ کامنت‌های یک پست، همهٔ رزروهای یک هتل)، جهش حافظه در workerها، و تراکنش‌هایی که ردیف‌های مورد نیاز دیگران را قفل می‌کنند. نشانه‌های aggregate بیش از حد کوچک: قواعدی که در sagaها یا jobهای شبانه دوباره پیاده شده‌اند، رقابت «چک کن بعد درج کن» میان aggregateهای جدا، و جبران چیزهایی که باید ساده رد می‌شدند.

نشانهعلت محتملحرکت
ConcurrencyConflict زیاد روی یک نوع ریشهویرایش‌های بی‌ربط یک version مشترک دارنددر امتداد use caseهای متداخل بشکنید
زمان بارگذاری با عمر رکورد رشد می‌کندمجموعهٔ بی‌کران درون aggregateاقلام مجموعه را aggregate جدا با ارجاع id کنید
فرمان برای تصمیم به وضعیت دو aggregate نیاز داردinvariant گمشده یا شکستن غلطبخش‌ها را در یک aggregate (اغلب با نام تازه) ادغام کنید یا domain service به‌اضافهٔ event
saga قاعده‌ای را جبران می‌کند که هرگز نباید بشکندمرز بیش از حد کوچکاشیای آن قاعده را در یک aggregate جمع کنید
ریشه ۴۰ متد و ۱۵ مجموعه داردچند مفهوم در یکیaggregateهای پنهان را در زبان فراگیر پیدا کنید

راه درست: بدترین اندازه را با عدد تخمین بزنید (بخش سوم Vernon یک شمارش پشت‌پاکتی می‌کند و به "25 objects maximum total" می‌رسد)، value object را بر entity درونی ترجیح دهید، و نرخ تداخل و زمان بارگذاری را برای هر نوع aggregate در production بسنجید. فقط وقتی بشکنید که یک اندازه‌گیری یا قاعدهٔ تازه بخواهد.

ارجاع به aggregateهای دیگر با شناسه (قاعدهٔ ۳) حیاتی ​

به زبان ساده: سفارش id مشتری را به خاطر می‌سپارد، نه شیء مشتری را؛ هر وقت مشتری لازم شد، بیرون از سفارش درخواستش می‌کند.

بدفهمی رایج: «ارجاع شیئی به یک ریشهٔ دیگر اشکالی ندارد چون به ریشه اشاره می‌کند.» Vernon: نگه‌داشتن ارجاع "does not place the referenced aggregate inside the consistency boundary of the one referencing it"، اما تغییر هر دو در یک تراکنش و بار کردن هر دو در هر بار را بی‌نهایت آسان می‌کند.

تعریف: "Prefer references to external aggregates only by their globally unique identity, not by holding a direct object reference". aggregateهای وابسته پیش از صدا زدن ریشه جست‌وجو می‌شوند: "Use a repository or domain service to look up dependent objects ahead of invoking the aggregate behavior." در دیتابیس این معمولاً یعنی هیچ کلید خارجی (Foreign key) از مرز aggregate (و قطعاً از مرز context) عبور نمی‌کند؛ درون یک aggregate (order_lines.order_id) کلید خارجی بی‌اشکال است.

Identity contextCustomeraggregate rootCatalog contextProductaggregate rootSales contextOrdercustomerId: CustomerIDlines[].sku: SKUversionOrderRepository: Order onlyone Save = one transactionno FK to customers or products;ids are values copied inBilling contextPaymentorderId: stringFulfilment contextShipmentorderRef: OrderRefby idby idby idby idobject graph: no

تصویر پنج aggregate را در پنج context نشان می‌دهد. Order مقادیر customerId و sku را نگه می‌دارد؛ Payment و Shipment id سفارش را. فلش توپر ضربدرخورده گراف اشیایی است که نمی‌سازیم.

text
     Eloquent with object references (lazy loading)
1    $order = Order::find($id);                         SELECT * FROM orders WHERE id = ?
2    $order->customer->orders->count();                 SELECT customers; SELECT all orders of the customer
3    $order->customer->name = 'X'; $order->push();      saves order AND customer: two aggregates, one tx
     With identity references
1    $order = $orders->get($id);                         loads Order + lines only
2    $customer = $customers->get($order->customerId);    explicit, separate read, outside the root
3    $orders->save($order);                              one aggregate saved

سناریوی واقعی: صفحهٔ سفارشی که نام مشتری را با $order->customer->name نشان می‌دهد و سه refactor بعد، کنترلری که از همان مسیر مشتری را تغییر می‌دهد؛ job پس‌زمینه‌ای که سفارش را با همهٔ رابطه‌های تودرتو به یک payload چهار مگابایتی serialize می‌کند؛ طوفان N+1 هنگام فهرست کردن سفارش‌ها (مشکلات ORM). در Laravel، Model::preventLazyLoading() این وسوسه را دیدنی می‌کند: "After preventing lazy loading, Eloquent will throw a Illuminate\Database\LazyLoadingViolationException exception when your application attempts to lazy load any Eloquent relationship."

سبک ارجاعچه بار می‌شودتغییر هر دو در یک tx ممکن است؟توزیعکِی
ارجاع شیئی، eagerهمیشه هر دوبله، به‌آسانیمیان نودها ناممکنفقط درون یک aggregate
ارجاع شیئی، lazyدر اولین لمس، با کوئری پنهانبله، تصادفیمیان نودها ناممکناستثنای «دلیل چهارم» Vernon: نیاز سنجیدهٔ کارایی کوئری
شناسه (id نوع‌دار)فقط آنچه می‌خواهیدفقط اگر عمداً هر دو را بار کنیدمیان shardها و سرویس‌ها کار می‌کندپیش‌فرض میان aggregateها
شناسه + read modelنمای ازپیش‌ساختهنه (فقط خواندنی)همه‌جا کار می‌کندصفحه‌هایی که چند aggregate را با هم نشان می‌دهند (CQRS)

راه درست: id نوع‌دار (CustomerID، SKU، OrderRef) به‌جای شیء؛ سرویس application آنچه فرمان لازم دارد بار می‌کند و مقدارها را به ریشه می‌دهد؛ صفحه‌هایی که چند aggregate را ترکیب می‌کنند از مدل کوئری می‌خوانند، نه از مدل دامنه. Vernon این هزینه را صریح می‌گوید: "You may have to use multiple repositories in a single use case to populate views"، و وقتی سربار کوئری درد دارد به CQRS اشاره می‌کند.

سازگاری نهایی بیرون از مرز (قاعدهٔ ۴) حیاتی ​

به زبان ساده: وقتی یک تغییر باید تغییر دیگری در aggregate دیگری بسازد، یک event ثبت کنید و بگذارید تراکنشی جدا، کمی بعد، تغییر دوم را انجام دهد.

بدفهمی رایج: «سازگاری نهایی مصالحه‌ای فنی است که کسب‌وکار نمی‌پذیرد.» Vernon: "Domain experts are sometimes far more comfortable with the idea of delayed consistency than are developers." کسب‌وکارها خیلی پیش از دیتابیس‌ها با کاغذ و تأخیرهای چندساعته و چندروزه کار می‌کردند.

تعریف: Vernon از کتاب Evans (ص ۱۲۸) نقل می‌کند: "Any rule that spans AGGREGATES will not be expected to be up-to-date at all times. Through event processing, batch processing, or other update mechanisms, other dependencies can be resolved within some specific time." ریشه یک domain event ثبت می‌کند؛ هر مشترک aggregate خودش را بار می‌کند و در تراکنش خودش تغییرش می‌دهد؛ شکست‌ها آن‌قدر تکرار می‌شوند تا موفق شوند یا به سقف برسند، و بعد جبران یا گزارش می‌شوند.

کار چه کسی است؟ (Whose job is it?) معیار Vernon برای شکستن تساوی، از گفت‌وگویی با Evans: "ask whether it's the job of the user executing the use case to make the data consistent. If it is, try to make it transactionally consistent, but only by adhering to the other rules of aggregate. If it is another user's job, or the job of the system, allow it to be eventually consistent."

ONE transaction: Ordercheckout: factory + place()lines at most 20, total = sumINSERT orders, order_linesINSERT outbox(OrderPlaced)COMMIT (version 1)user's job: transactionalOutbox relaypublishes OrderPlacedInventory: reserve stocksaga step, may compensateBilling: capture paymentemits PaymentCapturedSales: order.markPaid()new tx, records OrderPaidOutbox relaypublishes OrderPaidFulfilment: new Shipmentonly from OrderPaidSales: order.markDispatched()on ParcelDispatchedDashed arrows = eventual consistency: async message, separate transaction, retried, idempotent"An order cannot be dispatched unpaid" holds because Shipment is only ever created from OrderPaid

این نقشه checkout را نشان می‌دهد. فقط جعبهٔ اول یک تراکنش است. هر فلش خط‌چین یک پیام ناهمگام است که در تراکنشی جدا روی یک aggregate پردازش می‌شود؛ قاعدهٔ «سفارش پرداخت‌نشده ارسال نمی‌شود» برقرار است چون Shipment فقط و فقط از OrderPaid ساخته می‌شود.

text
     Cross-aggregate rule "an order cannot be dispatched unpaid", eventually consistent
1    Sales     tx1: order.place()          -> outbox: sales.order.placed.v1
2    Inventory tx2: reserve stock (saga)    -> stock.reserved.v1   (or stock.rejected -> order.cancel())
3    Billing   tx3: capture payment         -> billing.payment.captured.v1
4    Sales     tx4: order.markPaid()        -> outbox: sales.order.paid.v1
5    Fulfilment tx5: Shipment::forPaidOrder(...)   only constructor of Shipment; no OrderPaid, no shipment
6    Fulfilment tx6: shipment.dispatch()    -> fulfilment.parcel.dispatched.v1
7    Sales     tx7: order.markDispatched()     root also refuses if not paid (defence in depth)

سناریوی واقعی: رزرو موجودی بعد از ثبت سفارش (saga با جبران اگر موجودی تمام شده باشد، Saga)؛ امتیاز وفاداری بعد از پرداخت؛ وضعیت یک backlog item بعد از رسیدن ساعت‌های تسک به صفر (بخش سوم Vernon، که تیم می‌پرسد کار چه کسی است و یک ترجیح workflow گمشده پیدا می‌کند)؛ به‌روزرسانی ایندکس جست‌وجو بعد از تغییر محصول؛ «کل خرید» مشتری روی صفحهٔ پروفایل.

گزینه برای قاعدهٔ میان‌aggregateیچطورمزیتهزینه
ادغام در یک aggregateهر دو بخش درون یک مرزاتمی، سادهaggregate بزرگ‌تر، رقابت بیشتر
Domain event + مشترکریشه ثبت می‌کند، outbox می‌رساند، handler aggregate دیگر را تغییر می‌دهدaggregate کوچک، مقیاس مستقلتأخیر، تلاش دوباره، idempotency
Saga / process managerماشین حالتی که فرمان و جبران صادر می‌کندچندمرحله‌ای، آگاه از شکستکد بیشتر، timeout (Saga)
job آشتی‌دهنده (Reconciliation)چک‌وتعمیر دوره‌ایآنچه eventها جا انداختند را می‌گیردتأخیر طولانی؛ هنوز event لازم است
دو aggregate، یک تراکنشهر دو را بار و ذخیره کنفوریقاعده را می‌شکند؛ فقط برای چهار دلیل قابل‌قبول

راه درست: برای هر قاعدهٔ میان‌aggregateی تأخیر قابل‌قبول را با خبرهٔ دامنه تعیین کنید، روی ریشه یک event با فعل گذشته ثبت کنید، آن را از طریق outbox منتشر کنید، هر handler را idempotent کنید (Idempotent Consumer و Inbox)، و به‌جای پنهان کردن تأخیر، وضعیت «در انتظار» را در UI نشان دهید.

یک aggregate در هر تراکنش، و استثناها مهم ​

به زبان ساده: یک فرمان یک نمونهٔ aggregate را تغییر می‌دهد و commit می‌کند؛ اگر use case بیشتر می‌خواهد، بقیه در تراکنش‌های بعدی انجام می‌شود.

بدفهمی رایج: «یک use case یعنی یک تراکنش.» Vernon: "A user goal should not be viewed as synonymous with transaction." یک checkout یک هدف کاربر است و چند تراکنش.

تعریف: "a properly designed bounded context modifies only one aggregate instance per transaction in all cases." Vernon سپس آن را "a rule of thumb" می‌نامد و چهار دلیل می‌آورد که متخصصان باتجربه آن را می‌شکنند.

دلیل (Vernon، بخش دوم)مثال در فروشگاه ماچرا قابل‌قبول استنرده
راحتی رابط کاربری (User interface convenience)ساختن ۳۰ سفارش پیش‌نویس از یک CSV در یک درخواستهر aggregate تازه invariantهای خودش را دارد؛ دسته‌ای = یکی‌یکیفقط ساختن aggregateهای مستقل
نبود سازوکار فنی (Lack of technical mechanisms)میزبان قدیمی بدون صف، تایمر یا worker پس‌زمینههیچ چیز دیگری سازگاری نهایی نمی‌دهددنبال «user-aggregate affinity» بگردید: یک کاربر برای هر دسته aggregate
تراکنش سراسری (Global transactions)سیاست سازمان two-phase commit (XA) را اجباری می‌کندسیاست است، نه طراحیاگر می‌شود در context خودتان باز یک aggregate را تغییر دهید
کارایی کوئری (Query performance)ارجاع شیئی مستقیم به یک بخش بزرگ و کم‌مصرف، با بارگذاری lazyنیاز سنجیدهٔ کاراییارجاع، به قرارداد، فقط‌خواندنی است
text
     Breaking the rule by accident (two aggregates, one tx, both versioned)
1    T1: load Order o-1 v3, Customer c-1 v9     T2: load Customer c-1 v9 (address change)
2    T1: order.place(); customer.addPoints()    T2: customer.changeAddress(); COMMIT -> c-1 v10
3    T1: COMMIT -> Customer conflict -> the ORDER placement fails because of an address edit

سناریوی واقعی: تراکنش «ثبت سفارش و به‌روزرسانی آمار مشتری» که هر بار مشتری پروفایلش را ویرایش می‌کند شکست می‌خورد؛ عملیات گروهی ادمین که ۵۰۰ سفارش را در یک تراکنش تغییر می‌دهد و ۴۰ ثانیه قفل نگه می‌دارد؛ job واردکردنی که مشکلی ندارد چون فقط aggregate می‌سازد.

راه درست: هر command handler = یک aggregate بار کن، یک متد صدا بزن، ذخیره کن؛ بقیه event handler است. اگر ناچارید قاعده را بشکنید، بنویسید کدام یک از چهار دلیل صدق می‌کند (یک خط ADR کافی است).

همروندی: version روی ریشه حیاتی ​

به زبان ساده: ریشه یک عدد دارد؛ هر ذخیره می‌گوید «فقط اگر عدد هنوز همانی است که خواندم» و یکی زیادش می‌کند؛ اگر کس دیگری زودتر ذخیره کرده بود، دوباره بار می‌کنید و از نو امتحان می‌کنید.

بدفهمی رایج: «ردیف ریشه فقط وقتی version لازم دارد که ستون‌های خود ریشه عوض شوند.» version از کل مرز محافظت می‌کند. اگر افزودن یک سطر فقط در order_lines درج کند و به orders دست نزند، دو addLine هم‌زمان هر دو ۱۹ سطر می‌بینند و هر دو commit می‌کنند: ۲۱ سطر. ذخیره باید همیشه ردیف ریشه را با چک version به‌روز کند، حتی وقتی فقط یک فرزند تغییر کرده.

تعریف: کنترل همروندی خوش‌بینانه (Optimistic concurrency) روی aggregate: ریشه یک version (عدد صحیح یا timestamp) دارد؛ بارگذاری آن را می‌خواند؛ ذخیره یک compare-and-set اجرا می‌کند (UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?)؛ صفر ردیف تحت‌تأثیر یعنی تغییر هم‌زمان، که application آن را به تلاش دوبارهٔ فرمان روی وضعیت تازه تبدیل می‌کند. مقالهٔ Vernon دقیقاً همین را فرض می‌گیرد: "Objects carry a version number that is incremented when changes are made and checked before they are saved to the database." قفل بدبینانه (Pessimistic locking، SELECT ... FOR UPDATE) جایگزین است وقتی تداخل زیاد است و کار میان خواندن و نوشتن کوتاه. جزئیات و مصالحه‌ها: قفل خوش‌بینانه و بدبینانه.

text
     Max-lines race, version on the root (the protected version)
     Client A                                         Client B
1    load o-1: 19 lines, version 7                    load o-1: 19 lines, version 7
2    addLine(tea): 20 lines OK                         addLine(cake): 20 lines OK (on its copy)
3    UPDATE orders ... WHERE version = 7 -> 1 row
4    rewrite lines; COMMIT (version 8)
5                                                      UPDATE orders ... WHERE version = 7 -> 0 rows
6                                                      ConcurrencyConflict -> retry: reload v8 (20 lines)
7                                                      addLine(cake) -> ErrTooManyLines (final, not retried)

سناریوی واقعی: دو کارشناس پشتیبانی که یک سفارش را ویرایش می‌کنند؛ خریداری با دو تب باز؛ webhook پرداخت و یک لغو که در یک ثانیه می‌رسند؛ همان پیام PaymentCaptured که دو بار به دو worker تحویل می‌شود.

راهبردچطورکِی می‌بردکِی می‌بازد
خوش‌بینانه، version روی ریشهcompare-and-set هنگام ذخیره، تکرار فرمانتداخل کم؛ aggregate کوچکaggregate داغ: طوفان تلاش دوباره
بدبینانه، FOR UPDATE روی ریشهقفل ردیف ریشه هنگام بارگذاری، درون txفرمان‌های کوتاه روی aggregate داغ (نقشهٔ صندلی)زمان فکر طولانی کاربر؛ انتظار قفل؛ deadlock
ایزولاسیون Serializable + تکرارSSI در PostgreSQL با SQLSTATE 40001 لغو می‌کندقواعدی که ردیف‌هایی را می‌پوشانند که قفلشان سخت استتکرار همه‌جا؛ wrapper تکرار لازم است
یک دستور اتمیUPDATE ... SET qty = qty - 1 WHERE qty > 0شمارنده با یک قاعدهقواعدی که کل aggregate را لازم دارند
انبارهٔ سندی، یک سند برای هر aggregateMongoDB: "write operations are atomic on the single-document level"aggregate در یک سند جا می‌شودویرایش هم‌زمان هنوز فیلد version می‌خواهد
نوشتن شرطی (Conditional write)condition expression در DynamoDB روی attribute نسخهaggregateهای key-valueخطای "The conditional request failed" را خودتان باید تکرار کنید

راه درست: ستون version روی جدول ریشه، repositoryای که همیشه آن را بالا می‌برد، خطای ConcurrencyConflict جدا از نقض قاعده، و یک حلقهٔ تکرار محدود (۳ تلاش با backoff کوچک) در سرویس application که aggregate را دوباره بار می‌کند. هرگز با ذخیرهٔ دوبارهٔ شیء کهنه تکرار نکنید. نقض قاعده (OrderRuleViolated، ErrTooManyLines) هرگز تکرار نمی‌شود. ویرایش هم‌زمانی میان نمونه‌های aggregate نیست که هماهنگ شود: هر نمونه version خودش را دارد، و دقیقاً به همین دلیل aggregate کوچک کمتر تداخل می‌کند.

چرخهٔ عمر و شناسهٔ aggregate مهم ​

به زبان ساده: aggregate با یک factory و یک id به دنیا می‌آید، با تغییر وضعیت‌های کسب‌وکار زندگی می‌کند و معمولاً با یک وضعیت پایانی (لغوشده، بسته، بایگانی) تمام می‌شود، نه با DELETE.

بدفهمی رایج: «دیتابیس هنگام insert به aggregate شناسه می‌دهد.» آن‌وقت eventهایی که پیش از اولین ذخیره ثبت شده‌اند id ندارند و factory نمی‌تواند id را به کسی بدهد. شناسه را پیش از ذخیره بسازید.

تعریف: چرخهٔ عمر شامل ساختن (factory، invariantها از لحظهٔ اول برقرار، event ساخت ثبت می‌شود)، بازسازی / تغییر / ذخیره (بارها، هر بار یک تراکنش و یک بالا رفتن version) و پایان (یک وضعیت کسب‌وکار) است. شناسهٔ ریشه سراسری است (UUIDv7، ULID، یا sequenceای که پیش از ساختن گرفته شده؛ تولید شناسه)؛ entityهای درونی فقط شناسهٔ محلی لازم دارند (جایگاه سطر یا SKU درون سفارش). Dahan دربارهٔ پایان عمر: "Orders aren’t deleted – they’re cancelled. There may also be fees incurred if the order is canceled too late." و دربارهٔ آغاز: "Customers don’t just appear out of thin air."

text
     Lifecycle of Order o-1 (UUIDv7 generated by the factory)
1    create   OrderFactory.fromCart -> Order(draft, version 0)   no event yet (draft is private)
2    place    order.place() -> OrderPlaced                         INSERT, version 1
3    pay      order.markPaid() -> OrderPaid                        UPDATE ... version 1 -> 2
4    dispatch order.markDispatched()                                  UPDATE ... version 2 -> 3
5    end      status dispatched; after 7 years -> archived by retention job (no DELETE by users)

سناریوی واقعی: «حذف مشتری» که باید «بستن حساب» با قواعد نگهداری باشد؛ «حذف محصول» که باید «توقف فروش» باشد تا سفارش‌های قدیمی هنوز نشانش دهند (مثال Dahan)؛ پاک‌سازی GDPR به‌شکل یک فرمان صریح که ناشناس می‌کند، نه حذف آبشاری میان aggregateها.

مرحلهصاحبکد نمونهقاعده
شناسهfactory یا تولیدکنندهٔ idStr::uuid7()، IDs.NextOrderID()پیش از اولین event
ساختنfactory / factory methodfromCart، reorder، Shipment::forPaidOrderکامل و معتبر، یا هیچ
تغییرمتدهای ریشهaddLine، place، markPaidیک tx، یک بالا رفتن version
بازسازیrepositoryreconstitute(...)بدون event، بدون قاعدهٔ ساخت
پایانمتد ریشهcancel، close، archiveیک وضعیت، با قواعد و eventهای خودش

راه درست: id از factory، سازنده‌ای که نتواند وضعیت نامعتبر بسازد، مسیر reconstitute جدا از ساختن، و تغییر وضعیت به‌جای حذف.

Aggregate و domain event حیاتی ​

به زبان ساده: وقتی ریشه تغییر می‌کند، یادداشت کوتاهی از آنچه رخ داد می‌نویسد؛ repository یادداشت‌ها را همراه aggregate ذخیره می‌کند و دیگران بعداً می‌خوانندشان.

بدفهمی رایج: «event را همان لحظه از درون ریشه dispatch کن.» اگر تراکنش بعدش rollback شود، مشترک‌ها به چیزی واکنش نشان داده‌اند که هرگز رخ نداده؛ اگر پردازه بعد از commit و پیش از dispatch بمیرد، event گم می‌شود.

تعریف: domain event "Something happened that domain experts care about" است (Evans). ریشه در طول فرمان‌ها eventها را در یک فهرست ثبت می‌کند؛ repository آن‌ها را در همان تراکنش aggregate در جدول outbox می‌نویسد؛ یک relay منتشرشان می‌کند؛ فهرست eventهای ریشه فقط بعد از commit پاک می‌شود. Evans eventها را مستقیم به مرز aggregate وصل می‌کند: "We keep the aggregates internally consistent at all times, while making other changes asynchronously." نام‌گذاری event، integration event و ترجمه موضوع Domain Events در برابر Integration Events است؛ relay در Outbox.

text
     Event recording with the outbox
1    order.place(now)                          root appends OrderPlaced to its pending list
2    repo.save(order): BEGIN
3      UPDATE orders ... WHERE version = 1
4      INSERT outbox(aggregate_id, aggregate_version = 2, 'sales.order.placed.v1', payload)
5    COMMIT                                    event and state are durable together
6    order.markCommitted(2)                    pending list cleared only now
7    relay: SELECT ... FROM outbox WHERE published_at IS NULL -> publish -> mark published

سناریوی واقعی: OrderPlaced رزرو Inventory و پرداخت Billing را شروع می‌کند؛ OrderCancelled با refundDue = true بازپرداخت را شروع می‌کند؛ ParcelDispatched به مشتری خبر می‌دهد و سفارش را ارسال‌شده می‌کند.

رویکردماندگار؟همان tx با aggregate؟محصول
ریشه مستقیم dispatch می‌کندنهنهضدالگو
event در Laravel با ShouldDispatchAfterCommitنه (درون‌پردازه‌ای بعد از commit)بعد از commit شلیک می‌شودLaravel 13: "This interface instructs Laravel to not dispatch the event until the current database transaction is committed."
جدول outbox + relayبلهبلههر دیتابیس SQL؛ Debezium برای relay مبتنی بر CDC (CDC)
انبارهٔ event-sourced (eventها خود وضعیت‌اند)بلهappend همان تراکنش استMarten روی PostgreSQL (Event Sourcing و CQRS)

راه درست: pendingEvents() و markCommitted() روی ریشه، درج outbox درون تراکنش repository، و ذخیرهٔ version aggregate با هر ردیف outbox تا مصرف‌کننده‌ها شکاف را تشخیص دهند و ترتیب هر aggregate را نگه دارند.

Aggregate و repository مهم ​

به زبان ساده: هر نوع aggregate یک repository دارد که کل aggregate را بار و ذخیره می‌کند؛ بخش‌های درونی هرگز repository خودشان را ندارند.

بدفهمی رایج: «هر جدول یک repository لازم دارد.» Evans: "Provide repositories only for aggregate roots that actually need direct access."

تعریف: repository "the illusion of an in-memory collection of all objects of that aggregate’s root type" می‌دهد (Evans). برای aggregate یعنی: get(id) یک ریشهٔ کاملاً بازسازی‌شده (یا proxy تنبلی که مثل آن رفتار کند) برمی‌گرداند، و save(root) کل مرز به‌اضافهٔ eventهای در انتظار را اتمی ذخیره می‌کند و version را اعمال می‌کند. interfaceها، متدهای کوئری، unit of work و نگاشت در Repositories و ماندگاری داده در طراحی است.

text
     Repository per child entity (anti-pattern)
1    $line = $lineRepo->find(42);  $line->quantity = 500;  $lineRepo->save($line);
2    -> no root loaded, no invariant checked, no version bumped, Order total now wrong
     One repository per aggregate
1    $order = $orders->get('o-1'); $order->addLine('mug', 2, $price); $orders->save($order);

سناریوی واقعی: OrderLineRepository که «برای کارایی» اضافه شد تا یک تعداد را عوض کند؛ ShipmentItemRepository که اپلیکیشن اسکنر انبار از آن استفاده می‌کند و قواعد بسته‌بندی مرسوله را دور می‌زند.

پرسش repositoryجواب برای aggregate
برای هر نوع aggregate چند تا؟یکی
get چه برمی‌گرداند؟ریشه با همهٔ آنچه درون مرز است
save چه می‌نویسد؟ردیف ریشه (با چک version)، ردیف‌های درونی، ردیف‌های outbox، در یک تراکنش
چه کسی صدایش می‌زند؟سرویس‌های application و event handlerها، نه خود ریشه («disconnected domain model» در نگاه Vernon شکلی از lazy loading است که توصیه نمی‌کند)
کوئری روی چند aggregate؟read model، نه repository (CQRS)

راه درست: repositoryهای فرزند را حذف کنید؛ هر نوشتن را از repository ریشه بگذرانید؛ صفحه‌های فهرستی سرویس کوئری خودشان را بگیرند.

Factoryها حیاتی ​

به زبان ساده: factory تکه‌کدی است که تنها کارش ساختن یک aggregate کامل و معتبر است، تا صدازننده‌ها هرگز دستی سرهمش نکنند.

بدفهمی رایج: «factory یعنی OrderFactory لاراولی در database/factories.» Eloquent model factoryها برای تست و seed وجود دارند؛ مستندات Laravel 13 با این جمله معرفی‌شان می‌کند: "When testing your application or seeding your database, you may need to insert a few records into your database." آن‌ها با دادهٔ جعلی ردیف می‌نویسند و دامنه را کامل دور می‌زنند. factory در DDD کد production درون دامنه است.

تعریف: Evans: "When creation of an entire, internally consistent aggregate, or a large value object, becomes complicated or reveals too much of the internal structure, factories provide encapsulation." و: "Create an entire aggregate as a piece, enforcing its invariants." factory می‌تواند یک شیء مستقل باشد ("which may itself have no responsibility in the domain model but is still part of the domain design")، یک factory method روی aggregate دیگر یا روی خود ریشه، یا برای حالت ساده یک سازندهٔ نام‌دار (Named constructor). بازسازی (Reconstitution)، یعنی ساختن دوباره از ذخیره، کار دیگری است: نباید event ساخت ثبت کند یا قواعد مخصوص ساختن را دوباره اجرا کند. سازوکار GoF (Factory Method، Abstract Factory، Builder) در الگوهای سازنده است.

نوعکجا زندگی می‌کندکِیمثال ما
سازندهٔ نام‌دار (Named constructor)متد static روی ریشهساختن ساده است: چند چکOrder::draft($id, $customerId, $currency)
factory مستقل (Standalone factory)شیئی شبیه domain serviceهمکار لازم دارد (فهرست قیمت، تولید id)، چندمرحله‌ایOrderFactory::fromCart()
factory method روی aggregate دیگرمتدی روی «وضعیت قبلی»کسب‌وکار می‌گوید X، Y را می‌سازدVernon: Product.planBacklogItem() یک BacklogItem تازه برمی‌گرداند
factory method روی خود ریشهمتدی روی همان نوعنمونهٔ تازه‌ای که از نمونهٔ قدیمی درمی‌آیدorder.reorder() یک Order تازه می‌سازد
factory در context دیگرhandler پیام + سازندهساختنی که با event آغاز می‌شودShipment::forPaidOrder() از OrderPaid
بازسازیrepository + reconstitute()بار کردن از ذخیرهبدون event، version بازگردانده می‌شود
Eloquent model factorydatabase/factoriesفقط تست و seederردیف orders می‌سازد، نه aggregate
text
     Factory method on another aggregate (Vernon, Part I)
1    product = productRepository.productOfId(tenant, productId)
2    backlogItem = product.planBacklogItem(summary, category, type, points)   Product creates, is NOT modified
3    backlogItemRepository.add(backlogItem)                                   only the new aggregate is saved
     "These redesigned methods have a [CQS] query contract, and act as factories." (Vernon)

نسخهٔ Dahan از همین ایده: "In any transition, the previous state is the aggregate root." مشتری از بازدیدکننده می‌آید، سفارش از سبد خرید، مرسوله از سفارش پرداخت‌شده. پرسیدن درست پیش از این چیز، چه وجود داشت؟ اغلب factory method درست را نشان می‌دهد.

سناریوی واقعی: ساختن سفارش از سبد خرید قیمت‌های فعلی Catalog، یک id، چک واحد پول و ادغام سطرها را لازم دارد: factory مستقل؛ دکمهٔ «دوباره بخر»: factory method روی سفارش قدیمی؛ مرسوله‌ای که فقط برای سفارش پرداخت‌شده باید وجود داشته باشد: factoryای که پیام سفارش پرداخت‌شده را می‌گیرد؛ پیش‌فاکتوری که با قیمت‌های قفل‌شده به سفارش تبدیل می‌شود: factory method روی Quote.

سازنده در برابر factoryسازنده (Constructor)Factory
همکارها (فهرست قیمت، ساعت، id)ناجور: هر صدازننده باید بدهدشانیک بار تزریق می‌شوند
چند مرحله، هر کدام اعتبارسنجی‌شدهفهرست پارامتر طولانیسرهم‌کردن خوانا
صدازننده به کلاس‌های concrete وابسته استبلهinterface پنهانشان می‌کند (Evans: "does not require the client to reference the concrete classes")
invariantهای نتیجهباید برقرار باشندباید برقرار باشند: factory متدهای ریشه را صدا می‌زند
مناسب برایریشه‌ها و value objectهای سادهسرهم‌کردن پیچیده، ساختن از وضعیت دیگر

راه درست: factory فرمان‌های خود ریشه (addLine) را صدا می‌زند تا نتواند invariantی را دور بزند؛ یا aggregate کامل برمی‌گرداند یا exception می‌دهد؛ شناسه را می‌سازد؛ بازسازی یک متد static جداست که فقط repositoryها استفاده‌اش می‌کنند؛ Eloquent factoryها در تست‌ها می‌مانند.

سازوکار (Mechanics) ​

schema یک aggregate حیاتی ​

sql
-- PostgreSQL. One aggregate (Order) = root table + inner table + outbox. Sales schema only.
CREATE TABLE orders (
  id           text PRIMARY KEY,                 -- UUIDv7 generated by the factory
  customer_id  text NOT NULL,                    -- reference by identity: NO foreign key to Identity
  currency     char(3) NOT NULL,
  status       text NOT NULL CHECK (status IN ('draft','placed','paid','dispatched','cancelled')),
  total_minor  bigint NOT NULL CHECK (total_minor >= 0),
  version      integer NOT NULL,                 -- the root's optimistic concurrency token
  created_at   timestamptz NOT NULL DEFAULT now(),
  updated_at   timestamptz
);
CREATE TABLE order_lines (
  order_id         text NOT NULL REFERENCES orders(id) ON DELETE CASCADE,  -- inside the boundary: FK is fine
  position         smallint NOT NULL,
  sku              text NOT NULL,                -- reference to Catalog by identity
  quantity         smallint NOT NULL CHECK (quantity BETWEEN 1 AND 50),
  unit_price_minor bigint NOT NULL,
  PRIMARY KEY (order_id, position)
);
CREATE TABLE outbox (
  id                bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  aggregate_type    text NOT NULL,
  aggregate_id      text NOT NULL,
  aggregate_version integer NOT NULL,
  event_type        text NOT NULL,
  payload           jsonb NOT NULL,
  created_at        timestamptz NOT NULL DEFAULT now(),
  published_at      timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

-- Save = compare-and-set on the root, ALWAYS, even if only lines changed.
BEGIN;
UPDATE orders SET status = 'draft', total_minor = 4550, version = version + 1, updated_at = now()
WHERE id = 'o-1' AND version = 7;              -- 0 rows -> ROLLBACK, raise ConcurrencyConflict
DELETE FROM order_lines WHERE order_id = 'o-1';
INSERT INTO order_lines VALUES ('o-1', 0, 'mug', 3, 1250), ('o-1', 1, 'tea', 1, 800);
COMMIT;

-- Pessimistic alternative for a hot aggregate: lock the ROOT row first, then work.
BEGIN;
SELECT version FROM orders WHERE id = 'o-1' FOR UPDATE;   -- second writer waits here
-- ... load lines, run the command in the application, write rows ...
COMMIT;

قیدهای CHECK دیتابیس تور ایمنی‌اند، نه مدل: ریشه ورودی بد را خیلی پیش از PostgreSQL با خطای دامنه رد می‌کند. به آنچه نیست دقت کنید: نه کلید خارجی به customers، نه کلید خارجی به products، نه جدول shipments در این schema.

الگوریتم ذخیره ​

text
     repository.save(order)
1    snapshot = order.snapshot()                    state + version read at load time
2    BEGIN
3    if version == 0: INSERT root (version 1)        duplicate id -> SQLSTATE 23505
4    else: UPDATE root ... WHERE id AND version      0 rows -> ROLLBACK -> ConcurrencyConflict
5    replace inner rows (or diff them)               only rows of THIS aggregate
6    INSERT outbox rows for pending events           same transaction
7    COMMIT                                          serialization failure -> 40001; deadlock -> 40P01
8    order.markCommitted(version + 1)                clear events only after a successful commit

جایگزین کردن ردیف‌های درونی (delete + insert) ساده‌ترین نگاشت درست برای aggregate کوچک است. aggregateهای بزرگ‌تر مجموعه را diff می‌کنند (درج تازه‌ها، به‌روزرسانی تغییرکرده‌ها، حذف برداشته‌شده‌ها)؛ ORMهایی با unit of work (Hibernate، Doctrine) این کار را با dirty checking می‌کنند، و Dahan وقتی فرزندان تازه چون مجموعهٔ ریشه تغییر کرده ذخیره می‌شوند اسمش را "persistence by reachability" می‌گذارد.

خطاهایی که می‌بینید ​

کجانشانهمعناتکرار؟
repository ما (هر دیتابیس SQL)UPDATE ... WHERE version = ? روی ۰ ردیف اثر می‌گذاردتغییر هم‌زمان همین aggregateبله: بار کن و فرمان را دوباره اجرا کن
PostgreSQLSQLSTATE 40001 serialization_failureتداخل REPEATABLE READ / SERIALIZABLE (سطوح ایزولاسیون)بله، کل تراکنش
PostgreSQLSQLSTATE 40P01 deadlock_detectedدو تراکنش با ترتیب قفل متفاوت (Deadlock)بله
PostgreSQLSQLSTATE 23505 unique_violationid یکسان دو بار درج شده (یا dedup در inbox)نه؛ «از قبل هست» حساب کنید
MySQL / InnoDBخطای 1213 (deadlock)، 1205 (lock wait timeout)، 1062 (duplicate entry)همان سه حالت با شماره‌گذاری MySQL1213 بله، 1205 شاید، 1062 نه
LaravelDB::transaction(..., attempts: 5)"the number of times a transaction should be retried when a deadlock occurs" (مستندات Laravel 13): فقط deadlockConcurrencyConflict ما حلقهٔ خودش را لازم دارد
LaravelIlluminate\Database\LazyLoadingViolationExceptionبعد از preventLazyLoading() یک رابطه lazy بار شدنه: کد را درست کنید
DynamoDB"The conditional request failed"condition expression (مثلاً version) نادرست بودبله، دوباره بار کنید
دامنهٔ ماOrderRuleViolated، ErrTooManyLines، ErrBadTransitionیک قاعدهٔ کسب‌وکار فرمان را رد کردهرگز

رفتار هر محصول ​

انبارهواحد طبیعی aggregateاتمی بودنتوکن همروندینکته
PostgreSQLردیف ریشه + ردیف‌های فرزندهر تعداد ردیف در یک تراکنشستون version، یا ستون سیستمی xminمرز aggregate انتخاب طراحی است، موتور آن را اعمال نمی‌کند
MySQL / InnoDBمثل PostgreSQLتراکنشیستون versionREPEATABLE READ پیش‌فرض خطای serialization نمی‌دهد؛ به چک version تکیه کنید
MongoDBیک سند برای هر aggregate"In MongoDB, write operations are atomic on the single-document level, even if modifying multiple values."فیلد version در filter دستور updateOneتراکنش چندسندی هست اما نشانهٔ بوی مرز است
DynamoDBیک item، یا یک partition key با چند itemنوشتن تک‌item؛ TransactWriteItems برای چند تاcondition expression روی attribute نسخهpartition key = id aggregate بار را پخش می‌کند
انبارهٔ event (Marten روی PostgreSQL)یک stream برای هر aggregateappend به یک streamexpected version هنگام append: Append(streamId, expectedVersion, events)snapshot هزینهٔ replay را محدود می‌کند (Event Sourcing)
Redisیک hash یا کلید JSON برای هر aggregateMULTI/EXEC با WATCHWATCH روی کلیدفقط اگر Redis منبع حقیقت باشد (Redis)

Go ​

مثال جاری در Go: aggregate Order در Sales با یک factory مستقل، یک factory method، بازسازی و ثبت event؛ قرارداد repository؛ یک repository درون‌حافظه‌ای و یکی برای PostgreSQL با قفل خوش‌بینانه و outbox؛ سرویس application با حلقهٔ تکرار؛ و Shipment در Fulfilment. ماژول در docs/snippets/ddd/aggregates-factories/go است؛ gofmt -l .، go vet ./... و go test ./... پاس می‌شوند (فقط stdlib).

ریشهٔ aggregate ​

line صادرنشده، رونوشت‌های فقط‌خواندنی LineView، قواعدی که پیش از هر تغییر چک می‌شوند، جمع مشتق‌شده و یک ماشین حالت:

go
// Package sales is the Sales bounded context. Order is its aggregate root:
// lines and totals live inside the boundary; Customer, Product and Shipment
// live in other aggregates and are referenced by identity only.
package sales

import (
	"errors"
	"fmt"
	"time"
)

type (
	// OrderID is the global identity of the Order aggregate.
	OrderID string
	// CustomerID references the Customer aggregate (Identity context) by id.
	CustomerID string
	// SKU references a Catalog product by id, never by object.
	SKU string
)

// Status is the Order state machine.
type Status string

const (
	Draft      Status = "draft"
	Placed     Status = "placed"
	Paid       Status = "paid"
	Dispatched Status = "dispatched"
	Cancelled  Status = "cancelled"
)

// Invariants owned by the root. They hold after every command, in one transaction.
const (
	MaxLines           = 20
	MaxQuantityPerLine = 50
)

// Domain errors are part of the model, phrased in the ubiquitous language.
var (
	ErrNotEditable       = errors.New("only a draft order can be edited")
	ErrTooManyLines      = fmt.Errorf("an order holds at most %d lines", MaxLines)
	ErrBadQuantity       = fmt.Errorf("quantity must be between 1 and %d", MaxQuantityPerLine)
	ErrCurrencyMismatch  = errors.New("all lines must use the order currency")
	ErrEmptyOrder        = errors.New("an order needs at least one line")
	ErrNoSuchLine        = errors.New("the order has no line for this SKU")
	ErrBadTransition     = errors.New("this status change is not allowed")
	ErrAlreadyDispatched = errors.New("the order is already dispatched; request a return instead")
)

// Money is a value object: amount in minor units plus ISO 4217 currency.
type Money struct {
	Minor    int64
	Currency string
}

// Add returns a new Money; both operands must share the currency.
func (m Money) Add(o Money) Money { return Money{Minor: m.Minor + o.Minor, Currency: m.Currency} }

// Times returns a new Money multiplied by n.
func (m Money) Times(n int) Money { return Money{Minor: m.Minor * int64(n), Currency: m.Currency} }

// line is an internal entity of the aggregate. It is unexported: outside code
// cannot hold a reference to it, so it cannot change a line behind the root's back.
type line struct {
	sku       SKU
	quantity  int
	unitPrice Money
}

// LineView is a read-only copy handed to callers.
type LineView struct {
	SKU       SKU
	Quantity  int
	UnitPrice Money
}

// Order is the aggregate root and the only entry point into the boundary.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []line
	version  int // optimistic concurrency token, owned by the root
	events   []Event
}

// AddLine adds or merges a line. All rules are checked before any state changes.
func (o *Order) AddLine(sku SKU, qty int, unitPrice Money) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	if unitPrice.Currency != o.currency {
		return ErrCurrencyMismatch
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			merged := o.lines[i].quantity + qty
			if qty < 1 || merged > MaxQuantityPerLine {
				return ErrBadQuantity
			}
			o.lines[i].quantity = merged
			return nil
		}
	}
	if qty < 1 || qty > MaxQuantityPerLine {
		return ErrBadQuantity
	}
	if len(o.lines) >= MaxLines {
		return ErrTooManyLines
	}
	o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPrice})
	return nil
}

// RemoveLine deletes the line for sku while the order is a draft.
func (o *Order) RemoveLine(sku SKU) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			o.lines = append(o.lines[:i], o.lines[i+1:]...)
			return nil
		}
	}
	return ErrNoSuchLine
}

// Place turns the draft into a commitment and records OrderPlaced.
// Stock reservation is NOT done here: Inventory reacts to the event (saga).
func (o *Order) Place(now time.Time) error {
	if o.status != Draft {
		return ErrBadTransition
	}
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	o.status = Placed
	o.record(OrderPlaced{OrderID: o.id, CustomerID: o.customer, Total: o.Total(), Lines: o.Lines(), At: now})
	return nil
}

// MarkPaid is called when Billing reports the payment captured.
func (o *Order) MarkPaid(paymentRef string, now time.Time) error {
	if o.status != Placed {
		return ErrBadTransition
	}
	o.status = Paid
	o.record(OrderPaid{OrderID: o.id, PaymentRef: paymentRef, Total: o.Total(), At: now})
	return nil
}

// MarkDispatched is called when Fulfilment reports ParcelDispatched.
// The rule "an order cannot be dispatched unpaid" is enforced across aggregates by the
// event flow (Fulfilment only creates shipments for OrderPaid); this check is
// the root's own defence of its state machine.
func (o *Order) MarkDispatched(now time.Time) error {
	if o.status != Paid {
		return ErrBadTransition
	}
	o.status = Dispatched
	return nil
}

// Cancel withdraws the order until it is dispatched.
func (o *Order) Cancel(reason string, now time.Time) error {
	switch o.status {
	case Dispatched:
		return ErrAlreadyDispatched
	case Cancelled:
		return ErrBadTransition
	}
	wasPaid := o.status == Paid
	o.status = Cancelled
	o.record(OrderCancelled{OrderID: o.id, Reason: reason, RefundDue: wasPaid, At: now})
	return nil
}

// Total is derived from the lines, so it can never disagree with them.
func (o *Order) Total() Money {
	t := Money{Currency: o.currency}
	for _, l := range o.lines {
		t = t.Add(l.unitPrice.Times(l.quantity))
	}
	return t
}

// Lines returns a copy; callers cannot mutate the internal slice.
func (o *Order) Lines() []LineView {
	out := make([]LineView, len(o.lines))
	for i, l := range o.lines {
		out[i] = LineView{SKU: l.sku, Quantity: l.quantity, UnitPrice: l.unitPrice}
	}
	return out
}

// ID returns the identity.
func (o *Order) ID() OrderID { return o.id }

// Customer returns the referenced customer id.
func (o *Order) Customer() CustomerID { return o.customer }

// Status returns the current state.
func (o *Order) Status() Status { return o.status }

// Version returns the optimistic concurrency token loaded from storage.
func (o *Order) Version() int { return o.version }

func (o *Order) record(e Event) { o.events = append(o.events, e) }

eventهایی که ریشه ثبت می‌کند ​

go
package sales

import "time"

// Event is a domain event recorded by the root. Events carry identities and
// values, never pointers to other aggregates. EventName is the class name in
// the ubiquitous language (OrderPlaced); the dotted, versioned integration
// type (sales.order.placed.v1) is assigned at the outbox, not here.
type Event interface{ EventName() string }

// OrderPlaced: the customer committed to buy. Inventory starts the
// stock-reservation saga from it; Billing starts collecting payment.
type OrderPlaced struct {
	OrderID    OrderID
	CustomerID CustomerID
	Total      Money
	Lines      []LineView
	At         time.Time
}

// EventName implements Event.
func (OrderPlaced) EventName() string { return "OrderPlaced" }

// OrderPaid: payment captured. Fulfilment creates a Shipment from it.
type OrderPaid struct {
	OrderID    OrderID
	PaymentRef string
	Total      Money
	At         time.Time
}

// EventName implements Event.
func (OrderPaid) EventName() string { return "OrderPaid" }

// OrderCancelled: the commitment was withdrawn; RefundDue tells Billing.
type OrderCancelled struct {
	OrderID   OrderID
	Reason    string
	RefundDue bool
	At        time.Time
}

// EventName implements Event.
func (OrderCancelled) EventName() string { return "OrderCancelled" }

// PendingEvents returns a copy of the events recorded since the last commit.
// The repository writes them to the outbox in the same transaction as the root.
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }

// MarkCommitted is called by the repository only after COMMIT succeeded:
// it clears the events and adopts the new version.
func (o *Order) MarkCommitted(newVersion int) {
	o.events = nil
	o.version = newVersion
}

Factory، factory method و بازسازی ​

OrderFactory.FromCart یک پیش‌نویس کامل را از سبد خرید و قیمت‌های Catalog سرهم می‌کند؛ Reorder یک factory method روی ریشه است؛ Reconstitute بدون event از ذخیره بازسازی می‌کند:

go
package sales

import (
	"errors"
	"fmt"
)

// ErrUnknownSKU means the price book has no price for a cart item.
var ErrUnknownSKU = errors.New("the catalog has no price for this SKU")

// PriceBook is what the factory needs from Catalog: a price snapshot per SKU.
// It is an interface owned by Sales (the consumer), implemented by an adapter.
type PriceBook interface {
	PriceOf(sku SKU, currency string) (Money, bool)
}

// IDs generates order identities before persistence (UUIDv7, ULID, ...).
type IDs interface{ NextOrderID() OrderID }

// CartItem is the input shape: what the shopper picked.
type CartItem struct {
	SKU      SKU
	Quantity int
}

// OrderFactory is a standalone factory. It owns the complex assembly
// (identity, price snapshot, line merging) and returns an Order whose
// invariants already hold, or an error. Clients never see a half-built Order.
type OrderFactory struct {
	IDs    IDs
	Prices PriceBook
}

// NewDraft creates an empty draft. Simple creation needs no factory object;
// this function is the "constructor" for the trivial case.
func NewDraft(id OrderID, customer CustomerID, currency string) (*Order, error) {
	if id == "" || customer == "" {
		return nil, errors.New("an order needs an id and a customer")
	}
	if len(currency) != 3 {
		return nil, errors.New("currency must be an ISO 4217 code")
	}
	return &Order{id: id, customer: customer, currency: currency, status: Draft}, nil
}

// FromCart builds a whole draft as one piece. Every line goes through
// AddLine, so the factory cannot bypass the root's invariants.
func (f OrderFactory) FromCart(customer CustomerID, currency string, items []CartItem) (*Order, error) {
	if len(items) == 0 {
		return nil, ErrEmptyOrder
	}
	o, err := NewDraft(f.IDs.NextOrderID(), customer, currency)
	if err != nil {
		return nil, err
	}
	for _, it := range items {
		price, ok := f.Prices.PriceOf(it.SKU, currency)
		if !ok {
			return nil, fmt.Errorf("%w: %s", ErrUnknownSKU, it.SKU)
		}
		if err := o.AddLine(it.SKU, it.Quantity, price); err != nil {
			return nil, fmt.Errorf("sku %s: %w", it.SKU, err)
		}
	}
	return o, nil
}

// Reorder is a factory method on the root: an existing Order creates a NEW
// Order aggregate (new identity, same lines, current prices). The old order is
// not modified, so only the new aggregate is saved in this transaction.
func (o *Order) Reorder(newID OrderID, prices PriceBook) (*Order, error) {
	n, err := NewDraft(newID, o.customer, o.currency)
	if err != nil {
		return nil, err
	}
	for _, l := range o.lines {
		p, ok := prices.PriceOf(l.sku, o.currency)
		if !ok {
			continue // discontinued products are dropped from a reorder
		}
		if err := n.AddLine(l.sku, l.quantity, p); err != nil {
			return nil, err
		}
	}
	if len(n.lines) == 0 {
		return nil, ErrEmptyOrder
	}
	return n, nil
}

// Snapshot is the persistence shape of the aggregate, used only by repositories.
type Snapshot struct {
	ID       OrderID
	Customer CustomerID
	Currency string
	Status   Status
	Lines    []LineView
	Version  int
}

// Snapshot exports the state for a repository.
func (o *Order) Snapshot() Snapshot {
	return Snapshot{ID: o.id, Customer: o.customer, Currency: o.currency, Status: o.status, Lines: o.Lines(), Version: o.version}
}

// Reconstitute rebuilds an Order from storage. It is a different job from
// creation: no events are recorded and creation-only rules (price lookup,
// "must start as draft") are not re-run. The stored data is trusted because
// only this aggregate ever wrote it.
func Reconstitute(s Snapshot) *Order {
	o := &Order{id: s.ID, customer: s.Customer, currency: s.Currency, status: s.Status, version: s.Version}
	for _, l := range s.Lines {
		o.lines = append(o.lines, line{sku: l.SKU, quantity: l.Quantity, unitPrice: l.UnitPrice})
	}
	return o
}

یک repository برای هر aggregate ​

go
package sales

import (
	"context"
	"errors"
)

// ErrConcurrencyConflict means another transaction saved this aggregate after
// we loaded it (the version column moved). Reload and re-run the command.
var ErrConcurrencyConflict = errors.New("order was modified concurrently")

// ErrNotFound means no aggregate has this identity.
var ErrNotFound = errors.New("order not found")

// OrderRepository is the one repository for the Order aggregate. There is no
// LineRepository: lines are reached only through the root.
type OrderRepository interface {
	Get(ctx context.Context, id OrderID) (*Order, error)
	// Save persists the whole aggregate and its pending events atomically,
	// failing with ErrConcurrencyConflict if the stored version moved.
	Save(ctx context.Context, o *Order) error
}

repository برای PostgreSQL: version روی ریشه، سطرها به‌عنوان یک واحد، outbox در همان تراکنش ​

روی database/sql نوشته شده (با درایور stdlib در pgx یا lib/pq). با pgx مستقیم، pgx.BeginFunc همین شکل را می‌دهد: "BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls [Tx.Commit] on db." با sqlc، "the WithTx method allows a Queries instance to be associated with a transaction"، پس کوئری‌های تولیدشده درون همان تراکنش Save اجرا می‌شوند.

go
// Package postgres implements sales.OrderRepository with database/sql
// (driver: pgx stdlib or lib/pq). One Save = one transaction = one aggregate.
package postgres

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"

	"academy/aggregates-factories/sales"
)

// OrderRepository maps the Order aggregate to orders, order_lines and outbox.
type OrderRepository struct{ DB *sql.DB }

// integrationTypes maps a domain event's class name to the dotted, versioned
// type of the published language. Only the outbox row carries the wire name.
var integrationTypes = map[string]string{
	"OrderPlaced":    "sales.order.placed.v1",
	"OrderPaid":      "sales.order.paid.v1",
	"OrderCancelled": "sales.order.cancelled.v1",
}

// Get loads the root and its lines in one transaction snapshot. It loads
// exactly the boundary: no customer, no product, no shipment.
func (r OrderRepository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	tx, err := r.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()

	s := sales.Snapshot{ID: id}
	err = tx.QueryRowContext(ctx,
		`SELECT customer_id, currency, status, version FROM orders WHERE id = $1`, id).
		Scan(&s.Customer, &s.Currency, &s.Status, &s.Version)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, sales.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	rows, err := tx.QueryContext(ctx,
		`SELECT sku, quantity, unit_price_minor FROM order_lines WHERE order_id = $1 ORDER BY position`, id)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		l := sales.LineView{UnitPrice: sales.Money{Currency: s.Currency}}
		if err := rows.Scan(&l.SKU, &l.Quantity, &l.UnitPrice.Minor); err != nil {
			return nil, err
		}
		s.Lines = append(s.Lines, l)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return sales.Reconstitute(s), tx.Commit()
}

// Save writes the whole aggregate. The root row is ALWAYS updated with a
// version check, even when only a line changed: that is what serialises two
// concurrent AddLine calls and protects the MaxLines invariant.
func (r OrderRepository) Save(ctx context.Context, o *sales.Order) error {
	s := o.Snapshot()
	tx, err := r.DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	newVersion := s.Version + 1
	if s.Version == 0 {
		_, err = tx.ExecContext(ctx,
			`INSERT INTO orders (id, customer_id, currency, status, total_minor, version)
			 VALUES ($1, $2, $3, $4, $5, 1)`,
			s.ID, s.Customer, s.Currency, s.Status, o.Total().Minor)
		if err != nil {
			return err // a duplicate id surfaces as SQLSTATE 23505
		}
	} else {
		res, err := tx.ExecContext(ctx,
			`UPDATE orders SET status = $2, total_minor = $3, version = version + 1, updated_at = now()
			 WHERE id = $1 AND version = $4`,
			s.ID, s.Status, o.Total().Minor, s.Version)
		if err != nil {
			return err
		}
		if n, _ := res.RowsAffected(); n == 0 {
			return sales.ErrConcurrencyConflict
		}
	}

	// Lines are part of the boundary: replace them as a unit.
	if _, err := tx.ExecContext(ctx, `DELETE FROM order_lines WHERE order_id = $1`, s.ID); err != nil {
		return err
	}
	for i, l := range s.Lines {
		if _, err := tx.ExecContext(ctx,
			`INSERT INTO order_lines (order_id, position, sku, quantity, unit_price_minor)
			 VALUES ($1, $2, $3, $4, $5)`,
			s.ID, i, l.SKU, l.Quantity, l.UnitPrice.Minor); err != nil {
			return err
		}
	}

	// Domain events go to the outbox in the SAME transaction (see the Outbox chapter).
	for _, e := range o.PendingEvents() {
		eventType, ok := integrationTypes[e.EventName()]
		if !ok {
			return fmt.Errorf("no integration type for %s", e.EventName())
		}
		payload, err := json.Marshal(e)
		if err != nil {
			return fmt.Errorf("encode %s: %w", e.EventName(), err)
		}
		if _, err := tx.ExecContext(ctx,
			`INSERT INTO outbox (aggregate_type, aggregate_id, aggregate_version, event_type, payload)
			 VALUES ('order', $1, $2, $3, $4)`,
			s.ID, newVersion, eventType, payload); err != nil {
			return err
		}
	}
	if err := tx.Commit(); err != nil {
		return err
	}
	o.MarkCommitted(newVersion) // clear events only after a successful commit
	return nil
}

repository درون‌حافظه‌ای با همان قرارداد ​

go
// Package memory is an in-memory OrderRepository with the same optimistic
// concurrency contract as the PostgreSQL one. Tests and the lab use it.
package memory

import (
	"context"
	"sync"

	"academy/aggregates-factories/sales"
)

// Repository stores snapshots (never live pointers), so two loads give two
// independent copies, exactly like two database reads.
type Repository struct {
	mu     sync.Mutex
	rows   map[sales.OrderID]sales.Snapshot
	Outbox []sales.Event
}

// New returns an empty repository.
func New() *Repository { return &Repository{rows: map[sales.OrderID]sales.Snapshot{}} }

// Get reconstitutes a fresh copy of the aggregate.
func (r *Repository) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	s, ok := r.rows[id]
	if !ok {
		return nil, sales.ErrNotFound
	}
	return sales.Reconstitute(s), nil
}

// Save is a compare-and-set on the version: the equivalent of
// UPDATE orders SET ..., version = version + 1 WHERE id = $1 AND version = $2.
func (r *Repository) Save(_ context.Context, o *sales.Order) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	current, exists := r.rows[o.ID()]
	switch {
	case !exists && o.Version() != 0:
		return sales.ErrNotFound
	case exists && current.Version != o.Version():
		return sales.ErrConcurrencyConflict
	}
	next := o.Snapshot()
	next.Version = o.Version() + 1
	r.rows[o.ID()] = next
	r.Outbox = append(r.Outbox, o.PendingEvents()...) // same "transaction"
	o.MarkCommitted(next.Version)
	return nil
}

سرویس application: یک aggregate در هر تراکنش، تکرار هنگام تداخل ​

go
// Package app holds application services: load one aggregate, call one
// command, save it. No business rule lives here.
package app

import (
	"context"
	"errors"
	"time"

	"academy/aggregates-factories/sales"
)

// MaxAttempts bounds the optimistic-concurrency retry loop.
const MaxAttempts = 3

// Retry re-runs fn while it fails with a concurrency conflict. fn must load
// the aggregate itself, so every attempt works on fresh state; re-saving the
// stale object would only conflict again (or worse, overwrite).
func Retry(ctx context.Context, fn func(ctx context.Context) error) error {
	var err error
	for attempt := 1; attempt <= MaxAttempts; attempt++ {
		err = fn(ctx)
		if !errors.Is(err, sales.ErrConcurrencyConflict) {
			return err
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Duration(attempt*attempt) * 5 * time.Millisecond):
		}
	}
	return err
}

// Orders is the Sales application service.
type Orders struct {
	Repo    sales.OrderRepository
	Factory sales.OrderFactory
	Now     func() time.Time
}

// AddLine: one command, one aggregate instance, one transaction.
func (s Orders) AddLine(ctx context.Context, id sales.OrderID, sku sales.SKU, qty int, price sales.Money) error {
	return Retry(ctx, func(ctx context.Context) error {
		o, err := s.Repo.Get(ctx, id)
		if err != nil {
			return err
		}
		if err := o.AddLine(sku, qty, price); err != nil {
			return err // a rule violation is final: never retried
		}
		return s.Repo.Save(ctx, o)
	})
}

// Checkout creates the Order through the factory and places it.
func (s Orders) Checkout(ctx context.Context, customer sales.CustomerID, currency string, items []sales.CartItem) (sales.OrderID, error) {
	o, err := s.Factory.FromCart(customer, currency, items)
	if err != nil {
		return "", err
	}
	if err := o.Place(s.Now()); err != nil {
		return "", err
	}
	return o.ID(), s.Repo.Save(ctx, o)
}

// MarkPaid handles Billing's PaymentCaptured message (eventual consistency
// between Billing and Sales). Redelivery is harmless: an order that is
// already paid is left alone.
func (s Orders) MarkPaid(ctx context.Context, id sales.OrderID, paymentRef string) error {
	return Retry(ctx, func(ctx context.Context) error {
		o, err := s.Repo.Get(ctx, id)
		if err != nil {
			return err
		}
		if o.Status() == sales.Paid {
			return nil // idempotent
		}
		if err := o.MarkPaid(paymentRef, s.Now()); err != nil {
			return err
		}
		return s.Repo.Save(ctx, o)
	})
}

Shipment در Fulfilment: فقط از سفارش پرداخت‌شده ساخته می‌شود ​

go
// Package fulfilment is the Fulfilment bounded context. Shipment is its own
// aggregate; it knows the order only as an identity copied from an event.
package fulfilment

import (
	"errors"
	"time"
)

type (
	// ShipmentID is the identity of the Shipment aggregate.
	ShipmentID string
	// OrderRef is Fulfilment's reference to a Sales order: an id, not an object.
	OrderRef string
)

// ShipmentStatus is the Shipment state machine.
type ShipmentStatus string

const (
	AwaitingPick ShipmentStatus = "awaiting_pick"
	Packed       ShipmentStatus = "packed"
	Dispatched   ShipmentStatus = "dispatched"
)

var (
	ErrNotPaid       = errors.New("a shipment can only be created for a paid order")
	ErrNothingToShip = errors.New("a shipment needs at least one parcel line")
	ErrNotPacked     = errors.New("only a packed shipment can be dispatched")
)

// OrderPaidMessage is Fulfilment's own translation of sales.order.paid.v1
// (an anticorruption layer keeps the Sales model out of this package).
type OrderPaidMessage struct {
	OrderID  string
	Paid     bool
	Lines    []PickLine
	Postcode string
}

// PickLine is a value object: what to pick, how many.
type PickLine struct {
	SKU      string
	Quantity int
}

// Shipment is the aggregate root.
type Shipment struct {
	id         ShipmentID
	order      OrderRef
	lines      []PickLine
	status     ShipmentStatus
	trackingNo string
	events     []any
}

// ParcelDispatched tells Sales (and the customer) that the parcel left.
type ParcelDispatched struct {
	ShipmentID ShipmentID
	OrderRef   OrderRef
	TrackingNo string
	At         time.Time
}

// NewShipmentForPaidOrder is the factory. The cross-aggregate rule "an order
// cannot be dispatched unpaid" is enforced here by construction: the only way to get a
// Shipment is from a paid-order message.
func NewShipmentForPaidOrder(id ShipmentID, msg OrderPaidMessage) (*Shipment, error) {
	if !msg.Paid {
		return nil, ErrNotPaid
	}
	if len(msg.Lines) == 0 {
		return nil, ErrNothingToShip
	}
	return &Shipment{
		id: id, order: OrderRef(msg.OrderID),
		lines: append([]PickLine(nil), msg.Lines...), status: AwaitingPick,
	}, nil
}

// MarkPacked records that the warehouse packed every line.
func (s *Shipment) MarkPacked() { s.status = Packed }

// Dispatch hands the parcel to a carrier and records the event.
func (s *Shipment) Dispatch(trackingNo string, now time.Time) error {
	if s.status != Packed {
		return ErrNotPacked
	}
	s.status, s.trackingNo = Dispatched, trackingNo
	s.events = append(s.events, ParcelDispatched{ShipmentID: s.id, OrderRef: s.order, TrackingNo: trackingNo, At: now})
	return nil
}

// Status returns the state.
func (s *Shipment) Status() ShipmentStatus { return s.status }

// Order returns the referenced order id.
func (s *Shipment) Order() OrderRef { return s.order }

// PendingEvents returns a copy of recorded events.
func (s *Shipment) PendingEvents() []any { return append([]any(nil), s.events...) }

تست‌ها ​

invariantها، رونوشت‌ها، ماشین حالت، eventها، factory، factory method و بازسازی:

go
package sales_test

import (
	"errors"
	"fmt"
	"testing"
	"time"

	"academy/aggregates-factories/sales"
)

var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)

func eur(minor int64) sales.Money { return sales.Money{Minor: minor, Currency: "EUR"} }

type seqIDs struct{ n int }

func (s *seqIDs) NextOrderID() sales.OrderID { s.n++; return sales.OrderID(fmt.Sprintf("o-%d", s.n)) }

type prices map[sales.SKU]int64

func (p prices) PriceOf(sku sales.SKU, cur string) (sales.Money, bool) {
	v, ok := p[sku]
	return sales.Money{Minor: v, Currency: cur}, ok
}

func draft(t *testing.T) *sales.Order {
	t.Helper()
	o, err := sales.NewDraft("o-1", "c-1", "EUR")
	if err != nil {
		t.Fatal(err)
	}
	return o
}

func TestTotalIsDerivedFromLines(t *testing.T) {
	o := draft(t)
	_ = o.AddLine("mug", 2, eur(1250))
	_ = o.AddLine("mug", 1, eur(1250)) // merged, not a second line
	_ = o.AddLine("tea", 1, eur(800))
	if got := o.Total().Minor; got != 4550 {
		t.Fatalf("total = %d, want 4550", got)
	}
	if n := len(o.Lines()); n != 2 {
		t.Fatalf("lines = %d, want 2", n)
	}
}

func TestInvariantsRejectBeforeChangingState(t *testing.T) {
	o := draft(t)
	for i := 0; i < sales.MaxLines; i++ {
		if err := o.AddLine(sales.SKU(fmt.Sprint("sku-", i)), 1, eur(100)); err != nil {
			t.Fatal(err)
		}
	}
	cases := []struct {
		name string
		err  error
		run  func() error
	}{
		{"21st line", sales.ErrTooManyLines, func() error { return o.AddLine("extra", 1, eur(100)) }},
		{"zero quantity", sales.ErrBadQuantity, func() error { return o.AddLine("sku-0", 0, eur(100)) }},
		{"over max per line", sales.ErrBadQuantity, func() error { return o.AddLine("sku-0", sales.MaxQuantityPerLine, eur(100)) }},
		{"other currency", sales.ErrCurrencyMismatch, func() error { return o.AddLine("x", 1, sales.Money{Minor: 1, Currency: "USD"}) }},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if err := c.run(); !errors.Is(err, c.err) {
				t.Fatalf("err = %v, want %v", err, c.err)
			}
			if n := len(o.Lines()); n != sales.MaxLines {
				t.Fatalf("state changed: %d lines", n)
			}
		})
	}
}

func TestLinesReturnsACopy(t *testing.T) {
	o := draft(t)
	_ = o.AddLine("mug", 1, eur(1250))
	o.Lines()[0].Quantity = 999     // mutating the copy...
	if o.Lines()[0].Quantity != 1 { // ...does not reach inside the boundary
		t.Fatal("internal line was modified from outside the root")
	}
}

func TestStateMachineAndEvents(t *testing.T) {
	o := draft(t)
	if err := o.Place(now); !errors.Is(err, sales.ErrEmptyOrder) {
		t.Fatalf("empty place: %v", err)
	}
	_ = o.AddLine("mug", 1, eur(1250))
	if err := o.MarkPaid("pay-1", now); !errors.Is(err, sales.ErrBadTransition) {
		t.Fatalf("pay a draft: %v", err)
	}
	if err := o.Place(now); err != nil {
		t.Fatal(err)
	}
	if err := o.AddLine("tea", 1, eur(800)); !errors.Is(err, sales.ErrNotEditable) {
		t.Fatalf("edit after place: %v", err)
	}
	if err := o.MarkDispatched(now); !errors.Is(err, sales.ErrBadTransition) {
		t.Fatalf("dispatch unpaid: %v", err)
	}
	_ = o.MarkPaid("pay-1", now)
	_ = o.MarkDispatched(now)
	if err := o.Cancel("changed mind", now); !errors.Is(err, sales.ErrAlreadyDispatched) {
		t.Fatalf("cancel dispatched: %v", err)
	}
	ev := o.PendingEvents()
	if len(ev) != 2 || ev[0].EventName() != "OrderPlaced" || ev[1].EventName() != "OrderPaid" {
		t.Fatalf("events = %v", ev)
	}
}

func TestFactoryBuildsAWholeValidAggregate(t *testing.T) {
	f := sales.OrderFactory{IDs: &seqIDs{}, Prices: prices{"mug": 1250, "tea": 800}}
	o, err := f.FromCart("c-1", "EUR", []sales.CartItem{{SKU: "mug", Quantity: 2}, {SKU: "tea", Quantity: 1}})
	if err != nil {
		t.Fatal(err)
	}
	if o.ID() != "o-1" || o.Status() != sales.Draft || o.Total().Minor != 3300 {
		t.Fatalf("got %s %s %d", o.ID(), o.Status(), o.Total().Minor)
	}
	if _, err := f.FromCart("c-1", "EUR", []sales.CartItem{{SKU: "ghost", Quantity: 1}}); !errors.Is(err, sales.ErrUnknownSKU) {
		t.Fatalf("unknown sku: %v", err)
	}
	if _, err := f.FromCart("c-1", "EUR", []sales.CartItem{{SKU: "mug", Quantity: 0}}); !errors.Is(err, sales.ErrBadQuantity) {
		t.Fatalf("factory must not bypass invariants: %v", err)
	}
}

func TestReorderIsAFactoryMethodOnTheRoot(t *testing.T) {
	old := draft(t)
	_ = old.AddLine("mug", 2, eur(1000))
	_ = old.AddLine("retired", 1, eur(500))
	n, err := old.Reorder("o-2", prices{"mug": 1250})
	if err != nil {
		t.Fatal(err)
	}
	if n.ID() != "o-2" || len(n.Lines()) != 1 || n.Total().Minor != 2500 {
		t.Fatalf("reorder = %s, %d lines, %d", n.ID(), len(n.Lines()), n.Total().Minor)
	}
	if old.Total().Minor != 2500 { // the source aggregate is untouched
		t.Fatal("reorder modified the old order")
	}
}

func TestReconstituteRecordsNoEvents(t *testing.T) {
	o := sales.Reconstitute(sales.Snapshot{ID: "o-9", Customer: "c-1", Currency: "EUR", Status: sales.Placed, Version: 7,
		Lines: []sales.LineView{{SKU: "mug", Quantity: 1, UnitPrice: eur(1250)}}})
	if len(o.PendingEvents()) != 0 || o.Version() != 7 || o.Status() != sales.Placed {
		t.Fatalf("reconstitute: events=%d version=%d status=%s", len(o.PendingEvents()), o.Version(), o.Status())
	}
}

همروندی: ذخیرهٔ کهنه رد می‌شود؛ invariant سقف سطرها از رقابت جان سالم به در می‌برد؛ تداخل روی وضعیت تازه تکرار می‌شود؛ eventها همراه aggregate در outbox می‌نشینند:

go
package app_test

import (
	"context"
	"errors"
	"fmt"
	"testing"
	"time"

	"academy/aggregates-factories/app"
	"academy/aggregates-factories/memory"
	"academy/aggregates-factories/sales"
)

func eur(minor int64) sales.Money { return sales.Money{Minor: minor, Currency: "EUR"} }

// seed stores a draft with n lines at version 1.
func seed(t *testing.T, repo *memory.Repository, n int) {
	t.Helper()
	o, _ := sales.NewDraft("o-1", "c-1", "EUR")
	for i := 0; i < n; i++ {
		_ = o.AddLine(sales.SKU(fmt.Sprint("sku-", i)), 1, eur(100))
	}
	if err := repo.Save(context.Background(), o); err != nil {
		t.Fatal(err)
	}
}

// Two clients load version 1; the first save wins, the second gets a conflict.
func TestStaleSaveIsRejected(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	seed(t, repo, 1)

	a, _ := repo.Get(ctx, "o-1")
	b, _ := repo.Get(ctx, "o-1")
	_ = a.AddLine("tea", 1, eur(800))
	_ = b.AddLine("cake", 1, eur(450))

	if err := repo.Save(ctx, a); err != nil {
		t.Fatal(err)
	}
	if err := repo.Save(ctx, b); !errors.Is(err, sales.ErrConcurrencyConflict) {
		t.Fatalf("second save: %v, want conflict", err)
	}
}

// The MaxLines invariant survives a race: 19 lines, two concurrent adds.
// One commits (20 lines); the other retries on fresh state and is refused.
func TestInvariantHoldsUnderConcurrency(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	seed(t, repo, sales.MaxLines-1)

	stale, _ := repo.Get(ctx, "o-1") // client B loaded before A committed
	svc := app.Orders{Repo: repo, Now: time.Now}
	if err := svc.AddLine(ctx, "o-1", "tea", 1, eur(800)); err != nil { // client A
		t.Fatal(err)
	}
	_ = stale.AddLine("cake", 1, eur(450)) // passes on B's stale copy (19 lines)
	if err := repo.Save(ctx, stale); !errors.Is(err, sales.ErrConcurrencyConflict) {
		t.Fatalf("stale save: %v", err)
	}
	// B retries the COMMAND through the service: reload, re-check, refuse.
	if err := svc.AddLine(ctx, "o-1", "cake", 1, eur(450)); !errors.Is(err, sales.ErrTooManyLines) {
		t.Fatalf("retry: %v, want ErrTooManyLines", err)
	}
	o, _ := repo.Get(ctx, "o-1")
	if len(o.Lines()) != sales.MaxLines {
		t.Fatalf("lines = %d", len(o.Lines()))
	}
}

// conflictOnce makes the first Save fail, as if another writer slipped in.
type conflictOnce struct {
	*memory.Repository
	fired bool
}

func (c *conflictOnce) Save(ctx context.Context, o *sales.Order) error {
	if !c.fired {
		c.fired = true
		return sales.ErrConcurrencyConflict
	}
	return c.Repository.Save(ctx, o)
}

func TestRetryReloadsAndSucceeds(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	seed(t, repo, 1)
	svc := app.Orders{Repo: &conflictOnce{Repository: repo}, Now: time.Now}
	if err := svc.AddLine(ctx, "o-1", "tea", 1, eur(800)); err != nil {
		t.Fatalf("retry should succeed: %v", err)
	}
	o, _ := repo.Get(ctx, "o-1")
	if o.Version() != 2 || len(o.Lines()) != 2 {
		t.Fatalf("version=%d lines=%d", o.Version(), len(o.Lines()))
	}
}

type ids struct{}

func (ids) NextOrderID() sales.OrderID { return "o-42" }

type book struct{}

func (book) PriceOf(sales.SKU, string) (sales.Money, bool) { return eur(1250), true }

func TestCheckoutWritesEventsWithTheAggregate(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	svc := app.Orders{Repo: repo, Factory: sales.OrderFactory{IDs: ids{}, Prices: book{}}, Now: time.Now}
	id, err := svc.Checkout(ctx, "c-1", "EUR", []sales.CartItem{{SKU: "mug", Quantity: 1}})
	if err != nil {
		t.Fatal(err)
	}
	if err := svc.MarkPaid(ctx, id, "pay-1"); err != nil {
		t.Fatal(err)
	}
	if err := svc.MarkPaid(ctx, id, "pay-1"); err != nil { // redelivered message
		t.Fatalf("redelivery: %v", err)
	}
	if len(repo.Outbox) != 2 {
		t.Fatalf("outbox = %d events, want placed + paid", len(repo.Outbox))
	}
}
go
package fulfilment_test

import (
	"errors"
	"testing"
	"time"

	"academy/aggregates-factories/fulfilment"
)

func TestShipmentOnlyFromPaidOrder(t *testing.T) {
	lines := []fulfilment.PickLine{{SKU: "mug", Quantity: 2}}
	if _, err := fulfilment.NewShipmentForPaidOrder("s-1", fulfilment.OrderPaidMessage{OrderID: "o-1", Lines: lines}); !errors.Is(err, fulfilment.ErrNotPaid) {
		t.Fatalf("unpaid: %v", err)
	}
	s, err := fulfilment.NewShipmentForPaidOrder("s-1", fulfilment.OrderPaidMessage{OrderID: "o-1", Paid: true, Lines: lines})
	if err != nil {
		t.Fatal(err)
	}
	if err := s.Dispatch("TRK1", time.Now()); !errors.Is(err, fulfilment.ErrNotPacked) {
		t.Fatalf("dispatch before pack: %v", err)
	}
	s.MarkPacked()
	if err := s.Dispatch("TRK1", time.Now()); err != nil {
		t.Fatal(err)
	}
	if s.Order() != "o-1" || len(s.PendingEvents()) != 1 {
		t.Fatalf("order=%s events=%d", s.Order(), len(s.PendingEvents()))
	}
}

غلط: aggregate غول‌پیکر Customer ​

go
// Package wrong shows the giant-aggregate anti-pattern: one Customer root that
// "owns" everything the customer ever touched. It compiles and it works in a
// demo; under real traffic it fails in the ways listed in the comments.
package wrong

import "time"

// Customer holds orders, their lines, shipments and invoices as one object graph.
// Every field is exported, so any caller can change any part without the root.
type Customer struct {
	ID        string
	Name      string
	Email     string
	Orders    []*Order // grows forever: loading a customer loads years of history
	Shipments []*Shipment
	Invoices  []*Invoice
	Version   int // one version for everything: editing an address conflicts with checkout
}

// Order is reachable and mutable from anywhere: no root guards its lines.
type Order struct {
	ID       string
	Lines    []*Line
	Total    int64 // stored, not derived: can disagree with Lines
	Status   string
	Shipment *Shipment // object reference across what should be a boundary
}

// Line is a child entity that has its own repository elsewhere (anti-pattern).
type Line struct {
	SKU      string
	Quantity int
	Price    int64
}

// Shipment belongs to Fulfilment but lives inside the Customer graph here.
type Shipment struct {
	ID         string
	Dispatched bool
	At         time.Time
}

// Invoice belongs to Billing but lives inside the Customer graph here.
type Invoice struct {
	ID     string
	Amount int64
	Paid   bool
}

// PlaceOrder modifies the customer, an order, a shipment and an invoice in one
// transaction. Two browser tabs of the same customer now conflict; the
// warehouse marking a shipment conflicts with Billing marking an invoice paid.
func (c *Customer) PlaceOrder(o *Order) {
	c.Orders = append(c.Orders, o)
	o.Shipment = &Shipment{ID: "s-" + o.ID}
	c.Shipments = append(c.Shipments, o.Shipment)
	c.Invoices = append(c.Invoices, &Invoice{ID: "i-" + o.ID, Amount: o.Total})
}

نگاه Go ​

ویژگی Goدغدغهٔ aggregateنکته
فیلدها و نوع‌های صادرنشدهپنهان‌کردن درونیاتline بیرون از sales ارجاع‌پذیر نیست؛ فقط ریشه تغییرش می‌دهد
برگرداندن رونوشت sliceنبود aliasing به درون مرزLines() slice تازه می‌سازد؛ slice درونی برگردانده‌شده اجازه می‌داد صدازننده سطرها را عوض کند
id نوع‌دار (type OrderID string)ارجاع با شناسهکامپایلر نمی‌گذارد CustomerID را جای OrderID بدهید
خطاهای sentinel + errors.Isنقض قاعده در برابر تداخلErrConcurrencyConflict تکرار می‌شود، ErrTooManyLines نه
Tx در database/sql + RowsAffectedcompare-and-set۰ ردیف = تداخل؛ defer tx.Rollback() بعد از commit بی‌خطر است
pgx.BeginFunc / WithTx در sqlcیک تراکنش برای هر ذخیرههمان الگوریتم با pgx یا کد تولیدشده
interface در دست مصرف‌کنندههمکارهای factoryPriceBook و IDs در Sales اعلام و با adapter پیاده می‌شوند
context.Contextتکرار محدودحلقهٔ تکرار با لغو درخواست متوقف می‌شود

Laravel ​

همین طراحی در یک اپلیکیشن Laravel 13 (PHP 8.4) با ماژول‌هایی زیر App\Modules. aggregate یک کلاس سادهٔ PHP است، نه مدل Eloquent؛ ماندگاری با query builder روی connection با نام sales است. PHP روی ماشین نویسنده نصب نیست؛ کد بازبینی شده، اجرا نشده.

ریشهٔ aggregate، valueها و خطاهایش ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;

/**
 * Order is the aggregate root of Sales. It is a plain PHP object, not an
 * Eloquent model: no public setters, no lazy relations, no save().
 * Lines live inside the boundary; Customer, Product and Shipment are ids.
 */
final class Order
{
    public const int MAX_LINES = 20;
    public const int MAX_QUANTITY_PER_LINE = 50;

    /** @var array<string, OrderLine> keyed by SKU */
    private array $lines = [];

    /** @var list<object> domain events recorded since the last commit */
    private array $events = [];

    private function __construct(
        public readonly string $id,
        public readonly string $customerId,
        public readonly string $currency,
        private OrderStatus $status,
        private int $version,
    ) {}

    /** Trivial creation: a named constructor is enough, no factory object needed. */
    public static function draft(string $id, string $customerId, string $currency): self
    {
        if ($id === '' || $customerId === '') {
            throw new OrderRuleViolated('An order needs an id and a customer.');
        }
        if (strlen($currency) !== 3) {
            throw new OrderRuleViolated('Currency must be an ISO 4217 code.');
        }

        return new self($id, $customerId, $currency, OrderStatus::Draft, 0);
    }

    /**
     * Reconstitution from storage: no events, no creation-only rules.
     *
     * @param list<OrderLine> $lines
     */
    public static function reconstitute(
        string $id, string $customerId, string $currency, OrderStatus $status, int $version, array $lines,
    ): self {
        $order = new self($id, $customerId, $currency, $status, $version);
        foreach ($lines as $line) {
            $order->lines[$line->sku] = $line;
        }

        return $order;
    }

    public function addLine(string $sku, int $quantity, Money $unitPrice): void
    {
        $this->assertStatus(OrderStatus::Draft, 'Only a draft order can be edited.');
        if ($unitPrice->currency !== $this->currency) {
            throw new OrderRuleViolated('All lines must use the order currency.');
        }

        $existing = $this->lines[$sku] ?? null;
        $newQuantity = ($existing?->quantity ?? 0) + $quantity;
        if ($quantity < 1 || $newQuantity > self::MAX_QUANTITY_PER_LINE) {
            throw new OrderRuleViolated('Quantity must be between 1 and '.self::MAX_QUANTITY_PER_LINE.'.');
        }
        if ($existing === null && count($this->lines) >= self::MAX_LINES) {
            throw new OrderRuleViolated('An order holds at most '.self::MAX_LINES.' lines.');
        }

        $this->lines[$sku] = new OrderLine($sku, $newQuantity, $existing?->unitPrice ?? $unitPrice);
    }

    public function removeLine(string $sku): void
    {
        $this->assertStatus(OrderStatus::Draft, 'Only a draft order can be edited.');
        if (! isset($this->lines[$sku])) {
            throw new OrderRuleViolated("The order has no line for {$sku}.");
        }
        unset($this->lines[$sku]);
    }

    /** Stock is reserved by Inventory reacting to OrderPlaced (a saga), not here. */
    public function place(DateTimeImmutable $now): void
    {
        $this->assertStatus(OrderStatus::Draft, 'Only a draft order can be placed.');
        if ($this->lines === []) {
            throw new OrderRuleViolated('An order needs at least one line.');
        }
        $this->status = OrderStatus::Placed;
        $this->events[] = new OrderPlaced($this->id, $this->customerId, $this->total(), $this->lines(), $now);
    }

    public function markPaid(string $paymentRef, DateTimeImmutable $now): void
    {
        if ($this->status === OrderStatus::Paid) {
            return; // redelivered PaymentCaptured message: already done
        }
        $this->assertStatus(OrderStatus::Placed, 'Only a placed order can be paid.');
        $this->status = OrderStatus::Paid;
        $this->events[] = new OrderPaid($this->id, $paymentRef, $this->total(), $now);
    }

    public function markDispatched(): void
    {
        $this->assertStatus(OrderStatus::Paid, 'An order cannot be dispatched unpaid.');
        $this->status = OrderStatus::Dispatched;
    }

    public function cancel(string $reason, DateTimeImmutable $now): void
    {
        if ($this->status === OrderStatus::Dispatched) {
            throw new OrderRuleViolated('The order is already dispatched; request a return instead.');
        }
        if ($this->status === OrderStatus::Cancelled) {
            return;
        }
        $refundDue = $this->status === OrderStatus::Paid;
        $this->status = OrderStatus::Cancelled;
        $this->events[] = new OrderCancelled($this->id, $reason, $refundDue, $now);
    }

    /** Derived, never stored independently of the lines it sums. */
    public function total(): Money
    {
        $total = Money::zero($this->currency);
        foreach ($this->lines as $line) {
            $total = $total->add($line->subtotal());
        }

        return $total;
    }

    /** @return list<OrderLine> immutable value objects, safe to hand out */
    public function lines(): array
    {
        return array_values($this->lines);
    }

    public function status(): OrderStatus
    {
        return $this->status;
    }

    public function version(): int
    {
        return $this->version;
    }

    /** @return list<object> */
    public function pendingEvents(): array
    {
        return $this->events;
    }

    /** Called by the repository only after COMMIT succeeded. */
    public function markCommitted(int $newVersion): void
    {
        $this->events = [];
        $this->version = $newVersion;
    }

    private function assertStatus(OrderStatus $expected, string $message): void
    {
        if ($this->status !== $expected) {
            throw new OrderRuleViolated($message);
        }
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

/**
 * A line inside the Order boundary. It is immutable: the root replaces it
 * instead of letting callers change it, so handing it out is safe.
 */
final readonly class OrderLine
{
    public function __construct(
        public string $sku,
        public int $quantity,
        public Money $unitPrice,
    ) {}

    public function subtotal(): Money
    {
        return $this->unitPrice->times($this->quantity);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

/** Value object: amount in minor units plus ISO 4217 currency. */
final readonly class Money
{
    public function __construct(
        public int $minor,
        public string $currency,
    ) {}

    public static function zero(string $currency): self
    {
        return new self(0, $currency);
    }

    public function add(self $other): self
    {
        if ($other->currency !== $this->currency) {
            throw new OrderRuleViolated('Cannot add different currencies.');
        }

        return new self($this->minor + $other->minor, $this->currency);
    }

    public function times(int $n): self
    {
        return new self($this->minor * $n, $this->currency);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

enum OrderStatus: string
{
    case Draft = 'draft';
    case Placed = 'placed';
    case Paid = 'paid';
    case Dispatched = 'dispatched';
    case Cancelled = 'cancelled';
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use DomainException;

/** A business rule refused the command. Never retried. */
final class OrderRuleViolated extends DomainException {}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use RuntimeException;

/** The stored version moved after we loaded the aggregate. Reload and retry. */
final class ConcurrencyConflict extends RuntimeException {}

eventهایی که ریشه ثبت می‌کند ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;

final readonly class OrderPlaced
{
    /** @param list<OrderLine> $lines */
    public function __construct(
        public string $orderId,
        public string $customerId,
        public Money $total,
        public array $lines,
        public DateTimeImmutable $at,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;

final readonly class OrderPaid
{
    public function __construct(
        public string $orderId,
        public string $paymentRef,
        public Money $total,
        public DateTimeImmutable $at,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;

final readonly class OrderCancelled
{
    public function __construct(
        public string $orderId,
        public string $reason,
        public bool $refundDue,
        public DateTimeImmutable $at,
    ) {}
}

factory در معنای DDD (نه Eloquent factory) ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

/** What Sales needs from Catalog; implemented by an adapter in Infrastructure. */
interface PriceBook
{
    public function priceOf(string $sku, string $currency): ?Money;
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use Illuminate\Support\Str;

/**
 * Standalone DDD factory: assembles a whole, valid draft from a cart.
 * Every line goes through Order::addLine(), so the factory cannot bypass
 * an invariant. Not to be confused with Laravel's Eloquent model factories,
 * which build test rows and skip the domain entirely.
 */
final readonly class OrderFactory
{
    public function __construct(private PriceBook $prices) {}

    /** @param list<array{sku: string, quantity: int}> $items */
    public function fromCart(string $customerId, string $currency, array $items): Order
    {
        if ($items === []) {
            throw new OrderRuleViolated('An order needs at least one line.');
        }

        $order = Order::draft((string) Str::uuid7(), $customerId, $currency);
        foreach ($items as $item) {
            $price = $this->prices->priceOf($item['sku'], $currency)
                ?? throw new OrderRuleViolated("The catalog has no price for {$item['sku']}.");
            $order->addLine($item['sku'], $item['quantity'], $price);
        }

        return $order;
    }

    /** Factory method flavour: a new Order built from an old one, old one untouched. */
    public function reorder(Order $previous): Order
    {
        $order = Order::draft((string) Str::uuid7(), $previous->customerId, $previous->currency);
        foreach ($previous->lines() as $line) {
            $price = $this->prices->priceOf($line->sku, $previous->currency);
            if ($price !== null) {
                $order->addLine($line->sku, $line->quantity, $price);
            }
        }
        if ($order->lines() === []) {
            throw new OrderRuleViolated('Nothing from this order can be bought again.');
        }

        return $order;
    }
}

Repository: UPDATE شرطی، سطرها، outbox، یک تراکنش ​

query builder در Laravel قفل بدبینانه (sharedLock، lockForUpdate) را مستند کرده اما کمکی برای ستون version ندارد، پس قفل خوش‌بینانه یک update() شرطی است؛ مستندات می‌گوید "The update method returns the number of affected rows." و DB::transaction برایمان commit یا rollback می‌کند: "If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown."

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

/** One repository per aggregate. There is no OrderLineRepository. */
interface OrderRepository
{
    public function get(string $id): Order;

    /** Persists root, lines and pending events atomically; throws ConcurrencyConflict. */
    public function save(Order $order): void;
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Infrastructure;

use App\Modules\Sales\Domain\ConcurrencyConflict;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderCancelled;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderPaid;
use App\Modules\Sales\Domain\OrderPlaced;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\OrderStatus;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;

/**
 * Maps the Order aggregate to orders, order_lines and outbox with the query
 * builder. Optimistic locking is a conditional UPDATE on the root's version:
 * update() returns the number of affected rows, and 0 means someone else won.
 */
final readonly class DbOrderRepository implements OrderRepository
{
    /** Domain event class => dotted, versioned type of the published language. */
    private const array INTEGRATION_TYPES = [
        OrderPlaced::class => 'sales.order.placed.v1',
        OrderPaid::class => 'sales.order.paid.v1',
        OrderCancelled::class => 'sales.order.cancelled.v1',
    ];

    private ConnectionInterface $db;

    public function __construct()
    {
        $this->db = DB::connection('sales'); // Sales' own connection and DB user
    }

    public function get(string $id): Order
    {
        $row = $this->db->table('orders')->where('id', $id)->first()
            ?? throw new OrderRuleViolated("Order {$id} not found.");

        $lines = $this->db->table('order_lines')
            ->where('order_id', $id)
            ->orderBy('position')
            ->get()
            ->map(fn (object $l) => new OrderLine($l->sku, (int) $l->quantity, new Money((int) $l->unit_price_minor, $row->currency)))
            ->all();

        return Order::reconstitute($row->id, $row->customer_id, $row->currency, OrderStatus::from($row->status), (int) $row->version, $lines);
    }

    public function save(Order $order): void
    {
        $newVersion = $order->version() + 1;

        $this->db->transaction(function () use ($order, $newVersion): void {
            if ($order->version() === 0) {
                $this->db->table('orders')->insert([
                    'id' => $order->id,
                    'customer_id' => $order->customerId,
                    'currency' => $order->currency,
                    'status' => $order->status()->value,
                    'total_minor' => $order->total()->minor,
                    'version' => 1,
                ]);
            } else {
                // Always touch the root, even if only a line changed.
                $affected = $this->db->table('orders')
                    ->where('id', $order->id)
                    ->where('version', $order->version())
                    ->update([
                        'status' => $order->status()->value,
                        'total_minor' => $order->total()->minor,
                        'version' => $newVersion,
                        'updated_at' => now(),
                    ]);

                if ($affected === 0) {
                    throw new ConcurrencyConflict("Order {$order->id} changed since version {$order->version()}.");
                }
            }

            $this->db->table('order_lines')->where('order_id', $order->id)->delete();
            foreach ($order->lines() as $position => $line) {
                $this->db->table('order_lines')->insert([
                    'order_id' => $order->id,
                    'position' => $position,
                    'sku' => $line->sku,
                    'quantity' => $line->quantity,
                    'unit_price_minor' => $line->unitPrice->minor,
                ]);
            }

            // Domain events -> outbox, same transaction (see the Outbox chapter).
            foreach ($order->pendingEvents() as $event) {
                $this->db->table('outbox')->insert([
                    'aggregate_type' => 'order',
                    'aggregate_id' => $order->id,
                    'aggregate_version' => $newVersion,
                    'event_type' => self::INTEGRATION_TYPES[$event::class],
                    'payload' => json_encode($event, JSON_THROW_ON_ERROR),
                ]);
            }
        });

        $order->markCommitted($newVersion); // only after COMMIT
    }
}
php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    protected $connection = 'sales';

    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->string('id', 36)->primary();          // UUIDv7 in production
            $table->string('customer_id', 36)->index(); // id reference to Identity: no foreign key
            $table->char('currency', 3);
            $table->string('status', 16);
            $table->bigInteger('total_minor');
            $table->unsignedInteger('version');   // optimistic concurrency token of the root
            $table->timestamps();
        });

        Schema::create('order_lines', function (Blueprint $table) {
            $table->string('order_id', 36);
            $table->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete(); // inside the boundary
            $table->unsignedSmallInteger('position');
            $table->string('sku', 64);                // id reference to Catalog: no foreign key
            $table->unsignedSmallInteger('quantity');
            $table->bigInteger('unit_price_minor');
            $table->primary(['order_id', 'position']);
        });

        Schema::create('outbox', function (Blueprint $table) {
            $table->id();
            $table->string('aggregate_type', 32);
            $table->string('aggregate_id', 36);
            $table->unsignedInteger('aggregate_version');
            $table->string('event_type', 64);
            $table->json('payload');
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('published_at')->nullable()->index();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox');
        Schema::dropIfExists('order_lines');
        Schema::dropIfExists('orders');
    }
};

سرویس application با حلقهٔ تکرار خودش ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Application;

use App\Modules\Sales\Domain\ConcurrencyConflict;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\OrderFactory;
use App\Modules\Sales\Domain\OrderRepository;
use Closure;
use DateTimeImmutable;

/**
 * Application service: load one aggregate, call one command, save it.
 * DB::transaction(..., attempts: n) retries deadlocks only; an optimistic
 * conflict is our own exception, so the retry loop is ours too.
 */
final readonly class OrderService
{
    private const int MAX_ATTEMPTS = 3;

    public function __construct(
        private OrderRepository $orders,
        private OrderFactory $factory,
    ) {}

    public function addLine(string $orderId, string $sku, int $quantity, Money $unitPrice): void
    {
        $this->retryOnConflict(function () use ($orderId, $sku, $quantity, $unitPrice): void {
            $order = $this->orders->get($orderId);          // fresh state every attempt
            $order->addLine($sku, $quantity, $unitPrice);   // OrderRuleViolated is final
            $this->orders->save($order);
        });
    }

    /** @param list<array{sku: string, quantity: int}> $items */
    public function checkout(string $customerId, string $currency, array $items): string
    {
        $order = $this->factory->fromCart($customerId, $currency, $items);
        $order->place(new DateTimeImmutable());
        $this->orders->save($order);

        return $order->id;
    }

    /** Handles Billing's PaymentCaptured message: eventual consistency between aggregates. */
    public function markPaid(string $orderId, string $paymentRef): void
    {
        $this->retryOnConflict(function () use ($orderId, $paymentRef): void {
            $order = $this->orders->get($orderId);
            $order->markPaid($paymentRef, new DateTimeImmutable());
            $this->orders->save($order);
        });
    }

    private function retryOnConflict(Closure $command): void
    {
        for ($attempt = 1; ; $attempt++) {
            try {
                $command();

                return;
            } catch (ConcurrencyConflict $e) {
                if ($attempt >= self::MAX_ATTEMPTS) {
                    throw $e;
                }
                usleep($attempt * $attempt * 5_000);
            }
        }
    }
}

Fulfilment: Shipment و handlerی که از OrderPaid می‌سازدش ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Fulfilment\Domain;

use DateTimeImmutable;
use DomainException;

/**
 * Shipment is Fulfilment's aggregate. It knows the order only by id.
 * The only way to create one is the factory below, which demands a paid
 * order: "an order cannot be dispatched unpaid" holds by construction.
 */
final class Shipment
{
    /** @var list<object> */
    private array $events = [];

    /** @param list<array{sku: string, quantity: int}> $lines */
    private function __construct(
        public readonly string $id,
        public readonly string $orderId,
        private readonly array $lines,
        private string $status,
        private ?string $trackingNo = null,
    ) {}

    /** @param list<array{sku: string, quantity: int}> $lines */
    public static function forPaidOrder(string $id, string $orderId, bool $paid, array $lines): self
    {
        if (! $paid) {
            throw new DomainException('A shipment can only be created for a paid order.');
        }
        if ($lines === []) {
            throw new DomainException('A shipment needs at least one parcel line.');
        }

        return new self($id, $orderId, $lines, 'awaiting_pick');
    }

    public function markPacked(): void
    {
        $this->status = 'packed';
    }

    public function dispatch(string $trackingNo, DateTimeImmutable $now): void
    {
        if ($this->status !== 'packed') {
            throw new DomainException('Only a packed shipment can be dispatched.');
        }
        $this->status = 'dispatched';
        $this->trackingNo = $trackingNo;
        $this->events[] = new ParcelDispatched($this->id, $this->orderId, $trackingNo, $now);
    }

    public function status(): string
    {
        return $this->status;
    }

    /** @return list<object> */
    public function pendingEvents(): array
    {
        return $this->events;
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Fulfilment\Domain;

use DateTimeImmutable;

final readonly class ParcelDispatched
{
    public function __construct(
        public string $shipmentId,
        public string $orderId,
        public string $trackingNo,
        public DateTimeImmutable $at,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Fulfilment\Application;

use App\Modules\Fulfilment\Domain\Shipment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Consumes sales.order.paid.v1 (relayed from the Sales outbox). One message,
 * one new Shipment aggregate, one Fulfilment transaction. The inbox row makes
 * a redelivered message a no-op.
 *
 * @param array{event_id: string, order_id: string, lines: list<array{sku: string, quantity: int}>} $payload
 */
final class CreateShipmentWhenOrderPaid implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    public function __construct(public array $payload) {}

    public function handle(): void
    {
        DB::connection('fulfilment')->transaction(function (): void {
            $db = DB::connection('fulfilment');
            if ($db->table('inbox')->insertOrIgnore(['event_id' => $this->payload['event_id']]) === 0) {
                return; // already processed
            }

            $shipment = Shipment::forPaidOrder(
                (string) Str::uuid7(),
                $this->payload['order_id'],
                paid: true, // the event type itself is the proof of payment
                lines: $this->payload['lines'],
            );

            $db->table('shipments')->insert([
                'id' => $shipment->id,
                'order_id' => $shipment->orderId, // an id, never a foreign key into Sales
                'status' => $shipment->status(),
                'version' => 1,
            ]);
        });
    }

    /** @return list<int> */
    public function backoff(): array
    {
        return [1, 5, 30];
    }
}

تست‌های Pest ​

php
<?php

declare(strict_types=1);

use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderFactory;
use App\Modules\Sales\Domain\OrderPaid;
use App\Modules\Sales\Domain\OrderPlaced;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\OrderStatus;
use App\Modules\Sales\Domain\PriceBook;

function eur(int $minor): Money
{
    return new Money($minor, 'EUR');
}

function priceBook(array $prices): PriceBook
{
    return new class($prices) implements PriceBook
    {
        public function __construct(private array $prices) {}

        public function priceOf(string $sku, string $currency): ?Money
        {
            return isset($this->prices[$sku]) ? new Money($this->prices[$sku], $currency) : null;
        }
    };
}

it('derives the total from its lines and merges the same SKU', function () {
    $order = Order::draft('o-1', 'c-1', 'EUR');
    $order->addLine('mug', 2, eur(1250));
    $order->addLine('mug', 1, eur(1250));
    $order->addLine('tea', 1, eur(800));

    expect($order->total()->minor)->toBe(4550)
        ->and($order->lines())->toHaveCount(2);
});

it('refuses the 21st line and leaves state unchanged', function () {
    $order = Order::draft('o-1', 'c-1', 'EUR');
    foreach (range(1, Order::MAX_LINES) as $i) {
        $order->addLine("sku-{$i}", 1, eur(100));
    }

    expect(fn () => $order->addLine('extra', 1, eur(100)))->toThrow(OrderRuleViolated::class)
        ->and($order->lines())->toHaveCount(Order::MAX_LINES);
});

it('walks the state machine and records events', function () {
    $order = Order::draft('o-1', 'c-1', 'EUR');
    $order->addLine('mug', 1, eur(1250));

    expect(fn () => $order->markDispatched())->toThrow(OrderRuleViolated::class, 'An order cannot be dispatched unpaid.');

    $order->place(new DateTimeImmutable());
    expect(fn () => $order->addLine('tea', 1, eur(800)))->toThrow(OrderRuleViolated::class);

    $order->markPaid('pay-1', new DateTimeImmutable());
    $order->markPaid('pay-1', new DateTimeImmutable()); // redelivery: no second event

    expect($order->status())->toBe(OrderStatus::Paid)
        ->and(array_map(fn (object $e) => $e::class, $order->pendingEvents()))
        ->toBe([OrderPlaced::class, OrderPaid::class]);
});

it('builds a whole valid order in the factory and cannot bypass invariants', function () {
    $factory = new OrderFactory(priceBook(['mug' => 1250, 'tea' => 800]));

    $order = $factory->fromCart('c-1', 'EUR', [['sku' => 'mug', 'quantity' => 2], ['sku' => 'tea', 'quantity' => 1]]);
    expect($order->total()->minor)->toBe(3300)
        ->and($order->status())->toBe(OrderStatus::Draft);

    expect(fn () => $factory->fromCart('c-1', 'EUR', [['sku' => 'ghost', 'quantity' => 1]]))
        ->toThrow(OrderRuleViolated::class);
    expect(fn () => $factory->fromCart('c-1', 'EUR', [['sku' => 'mug', 'quantity' => 0]]))
        ->toThrow(OrderRuleViolated::class);
});

it('reconstitutes without recording events', function () {
    $order = Order::reconstitute('o-9', 'c-1', 'EUR', OrderStatus::Placed, 7, []);

    expect($order->pendingEvents())->toBe([])
        ->and($order->version())->toBe(7);
});
php
<?php

declare(strict_types=1);

use App\Modules\Sales\Domain\ConcurrencyConflict;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Infrastructure\DbOrderRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('rejects a save based on a stale version', function () {
    $repo = new DbOrderRepository();
    $order = Order::draft('o-1', 'c-1', 'EUR');
    $order->addLine('mug', 1, new Money(1250, 'EUR'));
    $repo->save($order); // version 1

    $a = $repo->get('o-1');
    $b = $repo->get('o-1');
    $a->addLine('tea', 1, new Money(800, 'EUR'));
    $b->addLine('cake', 1, new Money(450, 'EUR'));

    $repo->save($a); // version 2
    expect(fn () => $repo->save($b))->toThrow(ConcurrencyConflict::class);

    expect(DB::connection('sales')->table('orders')->where('id', 'o-1')->value('version'))->toBe(2)
        ->and(DB::connection('sales')->table('order_lines')->where('order_id', 'o-1')->count())->toBe(2);
});

it('writes pending events to the outbox in the same transaction', function () {
    $repo = new DbOrderRepository();
    $order = Order::draft('o-2', 'c-1', 'EUR');
    $order->addLine('mug', 1, new Money(1250, 'EUR'));
    $order->place(new DateTimeImmutable());
    $repo->save($order);

    expect(DB::connection('sales')->table('outbox')->where('aggregate_id', 'o-2')->pluck('event_type')->all())
        ->toBe(['sales.order.placed.v1'])
        ->and($order->pendingEvents())->toBe([]);
});

غلط: aggregate به‌شکل گراف Eloquent ​

php
<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Anti-pattern: "the aggregate is the table". Customer is treated as the root
 * of orders, lines, shipments and invoices. Public attributes and relations
 * let any controller change any part; nothing guards an invariant.
 */
final class Customer extends Model
{
    protected $guarded = []; // every column writable from any request

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class); // lazy-loaded graph across three contexts
    }
}

// Typical controller code this design invites:
//
// $customer = Customer::find($id);
// $order = $customer->orders->last();            // lazy loads every order the customer ever made
// $order->lines[0]->quantity = 500;              // bypasses "max 50 per line"
// $order->total = 0;                             // stored total now disagrees with lines
// $order->shipment->status = 'dispatched';       // ships an unpaid order
// $customer->push();                             // saves the whole graph: one transaction, four contexts
//
// Order::where('status', 'placed')->update(['status' => 'paid']);
// Mass update: Laravel does not fire saving/updating model events here, so any
// "invariant" placed in an observer is skipped as well.

Eloquent factory هنوز به کار می‌آید، برای تست‌هایی که سریع ردیف می‌خواهند. آن را صریحاً دادهٔ تست برچسب بزنید و یادتان باشد که همهٔ قواعد Order را دور می‌زند:

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Persistence;

use Database\Factories\OrderRecordFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * Persistence-only Eloquent model for the orders table. It exists for tests,
 * seeders and reporting queries; it is NOT the Order aggregate and has no rules.
 */
final class OrderRecord extends Model
{
    /** @use HasFactory<OrderRecordFactory> */
    use HasFactory;

    protected $connection = 'sales';

    protected $table = 'orders';

    protected $keyType = 'string';

    public $incrementing = false;

    protected static function newFactory(): OrderRecordFactory
    {
        return OrderRecordFactory::new();
    }
}
php
<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Modules\Sales\Persistence\OrderRecord;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * TEST DATA ONLY. An Eloquent model factory writes rows with fake values and
 * bypasses every rule of the Order aggregate. It is not a DDD factory.
 *
 * @extends Factory<OrderRecord>
 */
final class OrderRecordFactory extends Factory
{
    protected $model = OrderRecord::class;

    public function definition(): array
    {
        return [
            'id' => (string) Str::uuid7(),
            'customer_id' => (string) Str::uuid7(),
            'currency' => 'EUR',
            'status' => 'placed',
            'total_minor' => fake()->numberBetween(100, 50_000), // may disagree with lines: fine for a fixture, wrong for a domain
            'version' => 1,
        ];
    }

    public function paid(): static
    {
        return $this->state(fn (array $attributes) => ['status' => 'paid']);
    }
}

نگاه Laravel ​

ویژگی Laravelدغدغهٔ aggregateنکته
کلاس سادهٔ PHP برای دامنه، query builder برای ماندگاریریشه از بخش‌هایش پاسداری می‌کندمدل Eloquent با $guarded = [] و رابطه‌های عمومی نمی‌تواند از invariantها پاسداری کند
DB::connection('sales')->transaction()یک aggregate در هر تراکنشبا exception rollback می‌کند؛ attempts: فقط deadlock را تکرار می‌کند
update() تعداد ردیف‌های اثرگرفته را برمی‌گرداندقفل خوش‌بینانهwhere('version', $v)->update([... 'version' => $v + 1])؛ ۰ = تداخل
lockForUpdate()قفل بدبینانه روی ریشهبرای aggregate داغ با فرمان‌های کوتاه (قفل‌ها)
Model::preventLazyLoading()ارجاع با شناسهبه‌جای عبور بی‌صدا از aggregateها LazyLoadingViolationException می‌اندازد
push()آشکارساز ضدالگو"save your model and all of its associated relationships": ذخیرهٔ گرافی که از aggregateها عبور می‌کند
به‌روزرسانی انبوه (Order::where(...)->update())دور زدن model eventهامستندات: "the models are never actually retrieved when issuing a mass update"، پس observerها هرگز اجرا نمی‌شوند
ShouldDispatchAfterCommitevent بعد از commit، درون پردازهماندگار نیست؛ برای هر چیزی که aggregate دیگری به آن وابسته است outbox بگذارید
job صف‌دار با insertOrIgnore روی inboxhandler میان‌aggregateی idempotentOrderPaid دوباره‌تحویل‌شده مرسولهٔ دوم نمی‌سازد
Str::uuid7()شناسه پیش از ماندگاریidهای مرتب در زمان که factory می‌سازد
Eloquent model factoryها (HasFactory، state())دادهٔ تستfactory در معنای DDD نیستند؛ دامنه را دور می‌زنند

حل مسئله‌های کلاسیک ​

یک aggregate غول‌پیکر Customer ​

راه‌حلچطورمزیتهزینه / محدودیت
شکستن بر اساس invariantهای واقعیCustomer (پروفایل)، Order، Shipment، Invoice به‌عنوان aggregateهای جدا با idتداخل بی‌ربط نیست؛ بارگذاری محدودصفحه‌ها read model می‌خواهند
بیرون بردن بخش‌های contextهای دیگرمرسوله‌ها به Fulfilment، فاکتورها به Billingهر context صاحب aggregateهای خودشevent میان contextها
نگه‌داشتن خلاصه، نه مجموعهCustomer.lifetimeValue که از eventهای OrderPaid به‌روز می‌شودCustomer کوچک می‌ماندعددی که در نهایت سازگار است

aggregate همان جدول است (Active Record همه‌جا) ​

راه‌حلچطورمزیتهزینه / محدودیت
کلاس دامنه + نگاشت ماندگاریکلاس سادهٔ Order، repository به orders و order_lines نگاشت می‌کندقواعد در یک جا؛ ذخیره‌سازی آزاد برای تغییرکد نگاشت
Eloquent فقط به‌عنوان مدل ماندگاریمدل OrderRecord فقط درون repositoryراحتی‌های Eloquent برای SQL می‌مانددو کلاس برای هر aggregate
حد وسط عمل‌گرامدل Eloquent بدون setter عمومی، رابطه‌های محافظت‌شده، متدهای رفتاریکد کمتربه‌آسانی فرسوده می‌شود؛ با تست‌های arch() در Pest اعمالش کنید

setterهای عمومی و ریشه‌های anemic ​

راه‌حلچطورمزیتهزینه / محدودیت
فرمان به‌جای settersetStatus('paid') می‌شود markPaid($ref)قاعده و event در یک متدتغییر نام صدازننده‌ها (زبان فراگیر)
valueهای درونی تغییرناپذیرOrderLine به‌صورت final readonly، ریشه جایگزینش می‌کنددادن سطرها به بیرون بی‌خطر استتخصیص حافظه در هر تغییر (ناچیز)
بردن منطق از سرویس‌ها به ریشهسرویس به «بار کن، صدا بزن، ذخیره کن» کوچک می‌شودهر قاعده یک خانه (Anemic در برابر Rich)هزینهٔ refactor

repository برای entityهای فرزند ​

راه‌حلچطورمزیتهزینه / محدودیت
حذف repository فرزندنوشتن‌ها را از OrderRepository عبور دهیدinvariantها و version همیشه اعمال می‌شوندبار کردن کل aggregate (که به‌هرحال کوچک است)
ارتقای فرزنداگر واقعاً تنها تغییر می‌کند، aggregate خودش با قواعد خودش شودمدل صادققواعد میان‌aggregateی event می‌شوند

منطق کسب‌وکار در سرویس‌های application به‌جای ریشه ​

راه‌حلچطورمزیتهزینه / محدودیت
بردن قواعد به متدهای ریشهif ($order->lines()->count() >= 20) به درون addLine می‌رودهر صدازننده قاعده را می‌گیردچیزی که ارزش گفتن داشته باشد نیست
domain service برای تصمیم‌های چند‌aggregateیچند aggregate را می‌خواند، تصمیم می‌گیرد، یکی را تغییر می‌دهدخانهٔ روشن برای سیاستی که در هیچ ریشه‌ای جا نمی‌شودباز هم یک aggregate در هر tx (سرویس‌ها)

قاعده‌ای که از aggregateها عبور می‌کند ​

راه‌حلچطورمزیتهزینه / محدودیت
ساختن از راه طراحیفقط یک factory می‌تواند aggregate وابسته را بسازد، از event درستقاعده شکستنی نیستجریان event لازم است
Saga با جبرانگام‌ها میان aggregateها؛ برگرداندن هنگام شکستشکست و timeout را مدیریت می‌کندپیچیدگی (Saga)
ادغام (مفهوم تازه)aggregate گمشده‌ای پیدا کنید که صاحب هر دو بخش استاتمیaggregate بزرگ‌تر؛ اندازه را بسنجید

انتخاب ​

وضعیتمرز پیشنهادیفن اضافهدلیل
سفارش با سطرها، جمع، وضعیتیک aggregate Orderversion روی ریشه؛ جمع مشتق‌شدهinvariantهای واقعی میان سطرها
پروفایل مشتری و سفارش‌هایشaggregateهای جداcustomerId روی سفارش؛ read model برای تاریخچههیچ invariantی هر دو را نمی‌پوشاند؛ تاریخچه بی‌کران است
سطح موجودی و سفارش‌هاجدا (Inventory در برابر Sales)saga: رزرو بعد از OrderPlaced، جبرانصاحبان و چرخه‌های عمر متفاوت
نقشهٔ صندلی یک اجرایک aggregate برای هر اجراFOR UPDATE روی ریشه؛ فرمان‌های کوتاهداغ، پررقابت، invariant «بدون رزرو دوباره»
پست وبلاگ و کامنت‌هاaggregateهای جداتعداد کامنت با eventکامنت‌ها بی‌کران رشد می‌کنند
حساب بانکی و سطرهای دفترشریشهٔ Account با موجودی؛ سطرها append می‌شوندخوش‌بینانه یا FOR UPDATE؛ snapshot موجودی«موجودی هرگز زیر صفر» invariant واقعی است
سبد خریدیک aggregate Cart برای هر خریدارfactory method cart.checkout() → Orderساختن از وضعیت قبلی
تغییر قیمت محصول و سفارش‌های بازجداsnapshot قیمت هنگام سفارش در سطرها کپی می‌شودسفارش نباید با تغییر catalog عوض شود

جریان تصمیم برای یک مرز پیشنهادی:

text
1  List the rules. For each: must it hold at every commit?          no  -> outside (eventual)
2  Whose job is it to make it true? The acting user?                 no  -> outside (eventual)
3  Do the objects in the rule fit in memory for every command?      no  -> split; summary values on the root
4  Will two users edit different parts at the same time, often?     yes -> split along those parts
5  Can the inside be mostly value objects?                          yes -> do it
6  Root, version, factory, one repository; events for the rest

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

aggregate واحدی است که از هر تغییر معماری جان سالم به در می‌برد. آنچه عوض می‌شود بهای عبور از مرز آن است.

Monolith: یک پردازه، یک دیتابیس ​

چطور دیده می‌شود: کلاس‌ها و جدول‌ها؛ وسوسه‌انگیز است که Order و Customer را در یک DB::transaction ذخیره کنید چون چیزی جلویتان را نمی‌گیرد.

ساده‌ترین استفادهٔ درست: همان قواعد به‌هرحال: یک aggregate در هر تراکنش، id میان aggregateها، ستون version، domain eventهایی که بعد از commit پخش می‌شوند. هزینهٔ درست انجام دادنش در monolith کم است، و همین است که گام‌های بعدی را ممکن می‌کند.

مثال (ساده): فروشگاهی کوچک: aggregate Order به‌صورت کلاس ساده، DbOrderRepository، و OrderPlaced که listener درون‌پردازه‌ای بعد از commit با آن ایمیل می‌فرستد.

مثال (در اندازهٔ production): monolithی با ۲۰ برنامه‌نویس و مدل Customer با ۳۰ رابطه؛ تداخل روی customers.updated_at در اوج بار؛ راه‌حل همان شکستن aggregate غول‌پیکر است، درون همان monolith و با یک read model برای صفحهٔ حساب کاربری.

Modular monolith و چند دیتابیس ​

چطور دیده می‌شود: هر ماژول (Sales، Fulfilment، Billing) صاحب aggregateها و جدول‌های خودش است (یک schema و role برای هر ماژول، Modular Monolith)؛ هیچ aggregateی از ماژول‌ها عبور نمی‌کند؛ ماژول‌ها با eventهای outbox و با id حرف می‌زنند.

مثال: کد همین صفحه در یک اپلیکیشن Laravel: OrderService با outbox روی connection به نام sales ذخیره می‌کند؛ یک relay، CreateShipmentWhenOrderPaid را روی صف می‌فرستد؛ handler فقط روی connection به نام fulfilment می‌نویسد.

text
     One deployable, two modules, two schemas
1    Sales:      BEGIN (sales) -> UPDATE orders v3->v4, INSERT outbox(order_paid) -> COMMIT
2    Relay:      SELECT unpublished outbox rows -> dispatch CreateShipmentWhenOrderPaid
3    Fulfilment: BEGIN (fulfilment) -> INSERT inbox(event_id), INSERT shipments -> COMMIT
4    No transaction touches both schemas; a crash between 1 and 3 is recovered by the relay

میکروسرویس (Microservices): هیچ aggregateی از سرویس‌ها عبور نمی‌کند ​

آنچه می‌ماند: aggregate، version، factory و eventهایش. relay مربوط به outbox به‌جای صف محلی روی broker منتشر می‌کند. هر نوع aggregate دقیقاً مال یک سرویس (context خودش) است، همان‌طور که مالکیت داده می‌خواهد (مالکیت داده).

آنچه می‌شکند: هر تراکنش میان‌aggregateی که در monolith از دست در رفته بود حالا saga لازم دارد؛ هر ارجاع شیئی میان contextها حالا فراخوانی API یا رونوشت محلی می‌خواهد؛ هر «اول aggregate دیگر را چک کن» به خواندن کهنه تبدیل می‌شود.

text
     sales-svc, billing-svc, fulfilment-svc; separate databases
1    sales-svc      Order.place()    -> outbox -> topic sales.order.placed.v1
2    billing-svc    Payment.capture() -> billing.payment.captured.v1
3    sales-svc      Order.markPaid() -> sales.order.paid.v1           (consumer is idempotent)
4    fulfilment-svc Shipment::forPaidOrder() -> shipments table       (inbox dedup on event_id)
5    fulfilment-svc Shipment.dispatch() -> fulfilment.parcel.dispatched.v1 -> sales-svc Order.markDispatched()
     Failure: payment captured but sales-svc down -> event waits in the broker; order shows "payment pending"

دادهٔ توزیع‌شده (Distributed data): shard، replica، cache و read model ​

کجا آزموده می‌شودچه می‌شکندپاسخ طراحی
Sharding / پارتیشن‌بندیتراکنشی میان دو shardکلید shard (Shard key) = id aggregate: هر aggregate همیشه روی یک shard است (Evans: "Keep an aggregate together on one server.")
replicaهای خواندنیبار از replica، ذخیره در primary: version کهنهaggregate را برای فرمان همیشه از primary بار کنید؛ replicaها فقط read model سرو می‌کنند (Replication)
cache از aggregateهارونوشت cacheشده با version قدیمی دوباره ذخیره می‌شودread model را cache کنید، نه aggregate را؛ یا همراه version cache کنید و بگذارید ذخیره چکش کند
read model (CQRS)صفحه‌ها دادهٔ چند aggregate را می‌خواهندeventها را به جدول‌های کوئری project کنید؛ هرگز از راه repositoryها میان aggregateها کوئری نزنید (الگوهای داده)
aggregate بزرگ در گذر زمانهزینهٔ بارگذاری رشد می‌کندفقط آنچه فرمان لازم دارد بار کنید (خلاصه روی ریشه)، snapshot برای aggregateهای event-sourced، بایگانی نمونه‌های قدیمی
چندمنطقه‌ای (Multi-region)دو منطقه یک aggregate را ویرایش می‌کنندیک منطقهٔ خانه برای هر aggregate (بر اساس id)، یا طراحی بی‌تعارض؛ چک version یک نویسنده می‌خواهد

مقالهٔ Helland نظریهٔ پشت این جدول است: entityها (aggregateهای ما) واحدی‌اند که می‌شود میان ماشین‌ها جابه‌جا کرد، و "Atomic Transactions Cannot Span Entities".

کارایی: فقط آنچه فرمان لازم دارد بار کنید ​

فنچطورکِیاحتیاط
مرز را کوچک نگه داریدریشه به‌اضافهٔ valueها؛ مجموعه فقط برای invariant واقعیهمیشه، اول از همهنرخ تداخل و زمان بارگذاری را برای هر نوع aggregate بسنجید
مقدارهای خلاصه روی ریشهlineCount، totalMinor که ریشه نگه می‌دارد؛ فرزندان فقط برای فرمان‌هایی که لازمشان دارند بار می‌شوندمجموعه‌های فرزند بزرگ که کم ویرایش می‌شوندریشه باید خلاصه‌ها را دقیق نگه دارد (آن‌ها هم invariant‌اند)
بخش lazy با دلیل سنجیدهبخش سوم Vernon: متن بزرگ کم‌مصرف بیرون برده یا lazy بار می‌شودیک attribute سنگینبه قرارداد فقط‌خواندنی؛ از طریقش تغییر ندهید
Snapshotaggregateهای event-sourced هر N event وضعیت را ذخیره و فقط دنباله را replay می‌کنندstreamهای طولانی eventschema اسنپ‌شات باید نسخه‌دار باشد (Event Sourcing)
Read model (CQRS)فهرست، جست‌وجو و داشبورد از projection می‌خوانند، نه از aggregateهر صفحه‌ای که چند aggregate را نشان می‌دهددر نهایت سازگار؛ تازگی داده را نشان دهید
بایگانی aggregateهای تمام‌شدهسفارش‌های ارسال‌شده یا لغوشدهٔ قدیمی‌تر از N سال به انبارهٔ سردجدول‌هایی که سال‌ها رشد می‌کنندقواعد نگهداری؛ گزارش‌ها از بایگانی می‌خوانند

مسیر مقیاس (Scaling path): 1×، 10×، 100× ​

مقیاسAggregateهارویه‌ها
1× (یک تیم، یک دیتابیس)aggregateهای کوچک، id میانشان، ستون versionتست واحد برای هر ریشه؛ event بعد از commit
10× (ماژول‌ها، چند تیم)aggregateها در مالکیت هر ماژول؛ outbox میان ماژول‌هامعیار نرخ تداخل و زمان بارگذاری برای هر نوع aggregate؛ dedup در inbox؛ read model برای صفحه‌ها
100× (سرویس‌ها، shardها)id aggregate به‌عنوان کلید shard و partition؛ یک سرویس برای هر contextsaga برای جریان‌های میان‌aggregateی، snapshot، ترتیب event برای هر aggregate (ترتیب)

آزمایشگاه: شکستن و محافظت از یک invariant ​

همه چیز با Go نصب‌شده آفلاین اجرا می‌شود؛ گام ۵ برای PostgreSQL به Docker نیاز دارد.

آماده‌سازی.

bash
cd docs/snippets/ddd/aggregates-factories/go
go test ./...
# ok  academy/aggregates-factories/app
# ok  academy/aggregates-factories/fulfilment
# ok  academy/aggregates-factories/sales
  1. invariantها پیش از تغییر رد می‌کنند. go test ./sales -run TestInvariantsRejectBeforeChangingState -v را اجرا کنید. همهٔ زیرتست‌ها پاس می‌شوند و تعداد سطرها ۲۰ می‌ماند. حالا در AddLine اول append کنید و بعد چک کنید (o.lines = append(...) و سپس if len(o.lines) > MaxLines { return ErrTooManyLines }) و دوباره اجرا کنید. فرمان هنوز خطای درست را برمی‌گرداند، اما --- FAIL: .../21st_line پیام state changed: 21 lines می‌دهد: رد شدن بعد از تغییر آمد. برگردانید.
  2. افزودن هم‌زمان نمی‌تواند از سقف عبور کند. go test ./app -run TestInvariantHoldsUnderConcurrency -v را اجرا کنید. ذخیرهٔ کهنهٔ کلاینت B خطای ErrConcurrencyConflict می‌گیرد؛ تکرارش ۲۰ سطر را دوباره بار می‌کند و ErrTooManyLines می‌گیرد.
  3. version باید فرزندان را هم بپوشاند. در memory/repository.go چک تداخل را طوری عوض کنید که فقط وقتی o.Status() با وضعیت ذخیره‌شده فرق دارد versionها را مقایسه کند (شبیه‌سازی «ریشه را فقط وقتی ستون‌های ریشه عوض شدند بالا ببر»). go test ./app را اجرا کنید: TestStaleSaveIsRejected با second save: <nil>, want conflict و TestInvariantHoldsUnderConcurrency با stale save: <nil> شکست می‌خورند. ذخیرهٔ کهنه بی‌صدا سطر A را با سطر B جایگزین کرد (به‌روزرسانی گم‌شده)؛ با ذخیره‌سازی ردیف‌به‌ردیف که فقط سطر تازه را درج می‌کند، همین اشتباه به ۲۱ سطر می‌رسد. برگردانید.
  4. ذخیرهٔ دوبارهٔ شیء کهنه هیچ کمکی نمی‌کند. در TestStaleSaveIsRejected بعد از چک تداخل، t.Logf("re-save stale b: %v", repo.Save(ctx, b)) را اضافه و با -v اجرا کنید: re-save stale b: order was modified concurrently چاپ می‌شود، چون b هنوز version 1 دارد و ذخیره‌گاه 2. فقط بار کردن دوباره (کاری که صدازننده‌های app.Retry می‌کنند) جلو می‌برد.
  5. دیتابیس واقعی. PostgreSQL را بالا بیاورید (docker run --rm -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:16-alpine)، فقط سه دستور CREATE TABLE و index را از schema اجرا کنید (نه بلوک‌های BEGIN را)، یک سفارش با INSERT INTO orders (id, customer_id, currency, status, total_minor, version) VALUES ('o-1', 'c-1', 'EUR', 'draft', 0, 7); بکارید، و در دو نشست psql اجرا کنید (ما این را روی PostgreSQL 16 اجرا کردیم؛ نشست ۲ تا commit نشست ۱ منتظر می‌ماند و بعد UPDATE 0 چاپ می‌کند):
sql
-- session 1                                         -- session 2
BEGIN;                                               BEGIN;
UPDATE orders SET version = version + 1
 WHERE id = 'o-1' AND version = 7;   -- UPDATE 1
                                                     UPDATE orders SET version = version + 1
                                                      WHERE id = 'o-1' AND version = 7;   -- waits for session 1
COMMIT;
                                                     -- UPDATE 0  (row re-checked after session 1 committed: version is 8)
                                                     ROLLBACK;  -- the application raises ConcurrencyConflict
  1. factory در برابر Eloquent factory. در یک اپلیکیشن Laravel با این snippetها، تست واحد Pest با عنوان "builds a whole valid order in the factory" را اجرا کنید، بعد با OrderRecord::factory()->create(['total_minor' => 1]) (factory دادهٔ تست در Laravel) یک ردیف درج کنید و آن را از راه DbOrderRepository::get() بار کنید. شیء دامنه دادهٔ ذخیره‌شده را می‌پذیرد، چون بازسازی به ذخیره اعتماد می‌کند. به همین دلیل fixtureهایی که با Eloquent factory ساخته شده‌اند هرگز نباید برای آزمودن قواعد دامنه به کار بروند.

بدفهمی‌های رایج ​

باورواقعیت
aggregate یعنی گراف بزرگ اشیایک مرز سازگاری است؛ بیشترشان یک ریشه به‌اضافهٔ value objectها هستند
هر entity ریشهٔ aggregate استentityهای درونی شناسهٔ محلی دارند و فقط از راه ریشه‌شان در دسترس‌اند
یک aggregate برای هر جدولaggregate اغلب چند جدول را می‌پوشاند؛ یک جدول هرگز چند aggregate را
همهٔ قواعد در یک تراکنشفقط invariantهای واقعی؛ بقیه نهایی، با event
ارجاع شیئی به ریشه‌های دیگر اشکالی نداردنوشتن چند aggregate و بارگذاری عظیم را آسان می‌کند؛ id به کار ببرید
version فقط وقتی مهم است که ستون‌های ریشه عوض شوندباید با هر ذخیرهٔ مرز عوض شود، وگرنه ویرایش فرزندان رقابت می‌کنند
هنگام تداخل، دوباره ذخیره کندوباره بار کن و فرمان را دوباره اجرا کن؛ شیء کهنه غلط است
DB::transaction(..., attempts: 5) تداخل خوش‌بینانه را حل می‌کندفقط deadlock را تکرار می‌کند؛ exception تداخل شما حلقهٔ خودش را می‌خواهد
model factoryهای Laravel همان factory در DDD هستندردیف تست می‌سازند و همهٔ قواعد را دور می‌زنند
بازسازی باید مثل ساختن اعتبارسنجی کند و event بدهدوضعیت مورد اعتماد را بی‌صدا بازمی‌گرداند؛ قواعد و event ساخت یک بار رخ داده‌اند
use caseها یک‌به‌یک تراکنش‌اند"A user goal should not be viewed as synonymous with transaction."
سازگاری نهایی یعنی «شاید هیچ‌وقت»یعنی در تأخیر توافق‌شده، با تکرار، idempotency و پایش
حذف aggregate امری عادی استبیشتر چرخه‌های عمر با یک وضعیت کسب‌وکار (لغوشده، بسته) تمام می‌شوند
aggregate کوچک یعنی بدون entity درونیentity درونی وقتی invariant واقعی می‌خواهدش بی‌اشکال است

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپارید
تعریفخوشه‌ای از entity + value، یک ریشه، یک مرز، یک تراکنش
ریشهتنها نقطهٔ ورود؛ invariantها را اعمال می‌کند؛ رفتار نشان می‌دهد؛ درونیات را پنهان می‌کند؛ صاحب version و eventهاست
قاعدهٔ ۱Model true invariants in consistency boundaries
قاعدهٔ ۲Design small aggregates: ریشه + valueها؛ entity فقط وقتی قاعده‌ای بخواهد
قاعدهٔ ۳Reference other aggregates by identity
قاعدهٔ ۴سازگاری نهایی بیرون از مرز، بعد از پرسیدن «کار چه کسی است؟»
تراکنش‌هایک نمونهٔ aggregate در هر تراکنش؛ چهار استثنای مستند
همروندیversion روی ریشه، با هر ذخیره بالا می‌رود؛ ۰ ردیف = تداخل؛ بار کن و تکرار کن؛ خطای قاعده هرگز تکرار نمی‌شود
بدبینانهFOR UPDATE روی ردیف ریشه برای فرمان‌های کوتاه روی aggregate داغ
Eventهاریشه ثبت می‌کند؛ repository در همان tx در outbox می‌نویسد؛ پاک‌کردن بعد از commit
Repositoryهایکی برای هر نوع aggregate؛ هیچ برای entityهای درونی
Factoryهاکامل و معتبر یا هیچ؛ مستقل، factory method، سازندهٔ نام‌دار؛ بازسازی جداست
Eloquentکلاس ساده برای ریشه‌ها؛ preventLazyLoading؛ بدون push() میان aggregateها؛ model factory = دادهٔ تست
توزیعid aggregate = کلید shard؛ هیچ aggregateی از سرویس‌ها یا shardها عبور نمی‌کند
بوی اندازهتداخل زیاد یا بارگذاری کند = خیلی بزرگ؛ قاعده در saga = خیلی کوچک

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — یک aggregate هم‌زمان کدام سه چیز را تعریف می‌کند؟ حیاتی ​

پاسخ

پاسخ: خوشه‌ای از اشیا با یک ریشه (تنها نقطهٔ ورود)، مجموعه‌ای از invariantها که بعد از هر تراکنش برقرارند، و واحد بار کردن، ذخیره و قفل (یک تراکنش، یک version). ببینید Aggregate و ریشه.

۲ — چهار قاعدهٔ Vernon را با کلمات خودش نام ببرید. مهم ​

پاسخ

پاسخ: Model True Invariants In Consistency Boundaries؛ Design Small Aggregates؛ Reference Other Aggregates By Identity؛ Use Eventual Consistency Outside the Boundary (بعد از پرسیدن اینکه کار چه کسی است). ببینید جدول قاعده‌ها.

۳ — چرا commit جو در مثال Product از Vernon شکست خورد و درسش چیست؟ مهم ​

پاسخ

پاسخ: Product، backlog itemها و releaseها و sprintها را زیر یک version داشت؛ backlog item بیل آن را بالا برد، پس زمان‌بندی release جو که بر version قدیمی تکیه داشت شکست خورد. aggregate بزرگ روی invariantهای ساختگی ساخته شده بود. بر اساس invariantهای واقعی بشکنید. ببینید Invariantها.

۴ — «سفارش پرداخت‌نشده ارسال نمی‌شود.» تراکنشی یا نهایی، و در طراحی ما چطور اعمال می‌شود؟ حیاتی ​

پاسخ

پاسخ: نهایی: کار سیستم (Billing و Fulfilment) است، نه خریدار. Fulfilment فقط از راه factoryای که پیام OrderPaid می‌گیرد Shipment می‌سازد، پس سفارش پرداخت‌نشده مرسوله‌ای برای ارسال ندارد؛ Order.markDispatched() هم جز برای پرداخت‌شده رد می‌کند. ببینید سازگاری نهایی.

۵ — دو کلاینت هم‌زمان به سفارشی با ۱۹ سطر یک سطر اضافه می‌کنند. چه چیزی تضمین می‌کند سفارش به ۲۱ سطر نرسد؟ حیاتی ​

پاسخ

پاسخ: repository همیشه ردیف ریشه را با WHERE version = ? به‌روز می‌کند، حتی وقتی فقط سطرها عوض شده‌اند. ذخیرهٔ دوم روی ۰ ردیف اثر می‌گذارد، تداخل می‌دهد، سرویس دوباره بار می‌کند (۲۰ سطر) و addLine با «سطر بیش از حد» رد می‌کند. ببینید همروندی.

۶ — چرا حلقهٔ تکرار باید aggregate را دوباره بار کند به‌جای ذخیرهٔ دوباره؟ مهم ​

پاسخ

پاسخ: شیء کهنه در برابر وضعیت قدیمی اعتبارسنجی شده و version قدیمی را دارد؛ ذخیرهٔ دوباره‌اش برای همیشه تداخل می‌دهد یا، بدون version، تغییر کلاینت دیگر را رونویسی می‌کند. اجرای دوبارهٔ فرمان روی وضعیت تازه invariantها را دوباره چک می‌کند.

۷ — دو تا از چهار دلیلی را که Vernon برای تغییر چند aggregate در یک تراکنش می‌پذیرد بگویید. تکمیلی ​

پاسخ

پاسخ: راحتی رابط کاربری (ساختن دسته‌ای aggregateهای مستقل)، نبود سازوکار فنی (بی‌پیام‌رسانی یا پردازش پس‌زمینه)، تراکنش سراسری که سیاست اجبار کرده، و کارایی کوئری (ارجاع مستقیم برای نیاز سنجیده). ببینید یک aggregate در هر تراکنش.

۸ — فرق OrderFactory::fromCart() و OrderRecord::factory() چیست؟ مهم ​

پاسخ

پاسخ: اولی factory در معنای DDD و کد production است: id می‌سازد، قیمت‌ها را می‌گیرد و از راه متدهای ریشه یک aggregate کامل و معتبر می‌سازد. دومی Eloquent model factory در Laravel برای تست و seeder است که با دادهٔ جعلی ردیف می‌نویسد و همهٔ قواعد دامنه را دور می‌زند. ببینید Factoryها.

۹ — چرا reconstitute() نباید OrderPlaced ثبت کند؟ مهم ​

پاسخ

پاسخ: بار کردن رویداد کسب‌وکار نیست. ثبت هنگام بار کردن یعنی هر بار خواندن سفارش، event تکراری منتشر شود؛ قواعد ساختن (گرفتن قیمت، «با پیش‌نویس شروع می‌شود») فقط مال لحظهٔ ساختن‌اند.

۱۰ — aggregate Customer شما در اوج بار مدام تداخل می‌دهد و ۸۰۰ میلی‌ثانیه طول می‌کشد بار شود. چه می‌کنید؟ مهم ​

پاسخ

پاسخ: می‌شکنیدش: پروفایل Customer، Order، Shipment، Invoice به‌عنوان aggregateهای جدا با ارجاع id؛ مقدارهای خلاصه (ارزش طول عمر) را روی مشتری نگه دارید که با event به‌روز می‌شوند؛ برای صفحهٔ حساب یک read model بسازید. ببینید Customer غول‌پیکر.

۱۱ — در دیتابیس shardشده، کلید shard جدول‌های orders و order_lines چه باید باشد و چرا؟ تکمیلی ​

پاسخ

پاسخ: id سفارش (id aggregate) برای هر دو، تا هر aggregate همیشه روی یک shard باشد و هر ذخیره یک تراکنش محلی. ببینید دادهٔ توزیع‌شده.

واژه‌نامه (Glossary) ​

واژهمعنا
تجمیع (Aggregate)خوشه‌ای از entityها و value objectها که برای سازگاری، بار کردن و ذخیره یک واحد حساب می‌شود
ریشهٔ تجمیع (Aggregate root)تنها entityای که از راهش به aggregate دسترسی می‌رسد؛ invariantهایش را اعمال می‌کند
entity درونی (Inner / local entity)entityای درون aggregate که فقط درون آن شناسه دارد (سطر سفارش)
شیء مقدار (Value object)شیء تغییرناپذیری که با مقدارهایش تعریف می‌شود (Money)؛ Entities & Value Objects
ناوردا (Invariant)قاعدهٔ کسب‌وکاری که بعد از هر تراکنش باید برقرار باشد
invariant واقعی / ساختگی (True / false invariant)قاعدهٔ واقعی کسب‌وکار در برابر قید ساختاری ساختهٔ برنامه‌نویس
مرز سازگاری (Consistency boundary)خطی که درونش invariantها فوراً برقرارند (سازگاری تراکنشی)
سازگاری تراکنشی (Transactional consistency)سازگاری فوری و اتمی درون یک تراکنش
سازگاری نهایی (Eventual consistency)سازگاری‌ای که بعداً، با event و تراکنش‌های جدا، به دست می‌آید
ارجاع با شناسه (Reference by identity)نگه‌داشتن id یک aggregate دیگر به‌جای ارجاع شیئی
Disconnected domain modelاستفاده از repository درون aggregate برای پیمایش؛ شکلی از lazy loading که Vernon توصیه نمی‌کند
کار چه کسی است؟ (Whose job is it?)آزمون: اگر کاربر عامل باید سازگارش کند، تراکنشی؛ وگرنه نهایی
User-aggregate affinityهر بار فقط یک کاربر روی یک دسته aggregate کار می‌کند؛ تراکنش چند‌aggregateی را امن‌تر می‌کند
همروندی خوش‌بینانه (Optimistic concurrency)خواندن بی‌قفل، چک version هنگام ذخیره، تکرار هنگام تداخل
ستون نسخه (Version column)عدد صحیحی روی ریشه که با هر ذخیره بالا می‌رود؛ توکن همروندی
قفل بدبینانه (Pessimistic locking)قفل کردن ردیف ریشه هنگام بار کردن (SELECT ... FOR UPDATE، lockForUpdate())
رقابت (Contention)تراکنش‌های زیادی که برای یک aggregate رقابت می‌کنند و تداخل یا انتظار می‌سازند
Compare-and-setبه‌روزرسانی فقط اگر مقدار فعلی برابر مقدار مورد انتظار باشد
تکرار با بار کردن دوباره (Retry with reload)هنگام تداخل، وضعیت تازه را بار کن و فرمان را دوباره اجرا کن
رویداد دامنه (Domain event)ثبت چیزی که رخ داده و خبرگان دامنه برایش اهمیت قائل‌اند
Outboxجدولی که در تراکنش aggregate نوشته می‌شود و eventها از آن منتقل می‌شوند
Inboxجدول idهای eventهای پردازش‌شده که مصرف‌کننده را idempotent می‌کند
Sagaدنباله‌ای از تراکنش‌های محلی با جبران، میان aggregateها یا سرویس‌ها
جبران (Compensation)کاری که گامی قبلی را از نظر معنایی برمی‌گرداند (آزادسازی موجودی، بازپرداخت)
Repositoryدسترسی شبه‌مجموعه به aggregateهای کامل از یک نوع
Unit of workسازوکاری که تغییرات را دنبال و در یک تراکنش می‌نویسد (Hibernate، Doctrine)
Persistence by reachabilityORM اشیای تازه‌ای را که به مجموعهٔ یک ریشهٔ ماندگار اضافه شده‌اند ذخیره می‌کند (Dahan)
کارخانه (Factory)شیء یا متدی که یک aggregate کامل و معتبر می‌سازد
Standalone factoryشیء دامنهٔ جدا برای ساختن پیچیده (OrderFactory)
Factory methodمتدی روی aggregate موجود که aggregate تازه‌ای می‌سازد (reorder، planBacklogItem)
سازندهٔ نام‌دار (Named constructor)متد static ساختن روی ریشه برای حالت‌های ساده (Order::draft)
بازسازی (Reconstitution)ساختن دوبارهٔ aggregate از ذخیره بدون قواعد ساختن یا event
Eloquent model factoryابزار تست و seed در Laravel که با دادهٔ جعلی ردیف مدل می‌سازد
Lazy loadingبار کردن رابطه در اولین دسترسی؛ خواندن‌های میان‌aggregateی را پنهان می‌کند
preventLazyLoadingکلیدی در Laravel که هنگام lazy load خطای LazyLoadingViolationException می‌اندازد
push()متد Eloquent که مدل و همهٔ رابطه‌های بارشده‌اش را ذخیره می‌کند
Snapshot (aggregate)شکل ماندگاری aggregate؛ در event sourcing وضعیت cacheشده برای کوتاه کردن replay
Read model / CQRSجدول‌های سمت کوئری ساخته‌شده از eventها برای صفحه‌هایی که چند aggregate را می‌پوشانند
کلید shard (Shard key)ستونی که تعیین می‌کند ردیف روی کدام shard ذخیره شود؛ برای aggregate همان id است
UUIDv7UUID مرتب در زمان، مناسب برای idهایی که پیش از ماندگاری ساخته می‌شوند
SQLSTATE 40001 / 40P01 / 23505در PostgreSQL: serialization failure / deadlock detected / unique violation
Two-phase commit (2PC)commit اتمی میان چند منبع؛ یکی از دلایل Vernon برای شکستن قاعده

منابع (References) ​

ساخته‌شده توسط Morteza Negahi