Skip to content

Data Patterns: Shared Database, Database per Service, CQS → CQRS, Read-Side Replication ​

"At its heart is the notion that you can use a different model to update information than the model you use to read information. For some situations, this separation can be valuable, but beware that for most systems CQRS adds risky complexity." — Martin Fowler، CQRS (bliki، ۱۴ ژوئیهٔ ۲۰۱۱)

خلاصه (Summary): وقتی هر context صاحب دادهٔ خودش است، دیگر نه join میان سرویس‌ها داریم و نه تراکنش مشترک؛ پس هر خواندنی که از چند context داده می‌خواهد به یک الگوی آگاهانه نیاز دارد: یا هنگام پرس‌وجو از صاحبان بپرسید و نتیجه‌ها را کنار هم بگذارید، یا یک read model نگه دارید که با eventهای صاحبان به‌روز می‌شود. CQS در سطح متد به CQRS در سطح مدل می‌رسد و هر قدم روی این طیف، استقلال خواندن را با قیمت تأخیر و سازوکار بیشتر می‌خرد. تمرکز (Focus): مسئلهٔ داده در میکروسرویس‌ها، shared database و معدود کاربردهای گذرای قابل‌قبولش، database per service (instance، schema، جدول خصوصی، polyglot persistence)، CQS از Meyer در Go و Laravel، CQRS از دو شیء تا دو انبار جدا (projection هم‌زمان در برابر ناهم‌زمان، و اینکه کِی نمی‌ارزد)، read model و projection (denormalised، برای هر صفحه، قابل بازسازی، نسخه‌دار، idempotent، catch-up و rebuild)، گزینه‌های رساندن داده به سمت خواندن (replica، logical replication، CDC با Debezium، projection مبتنی بر event، materialized view)، API composition در برابر read model، read-your-writes (version token، صبر برای projection، sticky read، خوش‌بینی UI)، خرابی‌های سازگاری نهایی، گزارش‌گیری، UI مبتنی بر وظیفه، event sourcing به‌عنوان گزینهٔ سمت نوشتن، و تست و پایش projectionها. هدف یادگیری (Learning goal): برای صفحه‌ای که از Sales، Fulfilment و Billing داده می‌خواهد بین API composition و read model انتخاب کنید و projection مربوط به OrderSummary را در Go و Laravel طوری بسازید که از تکرار، بی‌نظمی ترتیب eventها و بازسازی کامل سالم بیرون بیاید، با version token خواندنِ نوشتهٔ خود را تضمین کند و تأخیرش را به‌صورت metric نشان دهد.

این فصل گروه DD 03 (داده و API در میکروسرویس‌ها) را باز می‌کند و فرض می‌کند فصل‌های تاکتیکی را خوانده‌اید: aggregate واحد سازگاری است (Aggregates & Factories)، از راه repository ذخیره می‌شود (Repositories) و واقعیت‌هایی منتشر می‌کند که contextهای دیگر مصرف می‌کنند (Domain Events در برابر Integration Events). تصمیم اینکه کدام جدول مال کیست و چطور داده را از monolith جدا کنیم مال مالکیت داده در میکروسرویس‌ها است؛ این صفحه آن تصمیم را گرفته‌شده فرض می‌کند و الگوهای داده‌ای را نشان می‌دهد که یک توسعه‌دهنده روی آن پیاده می‌کند. لوله‌کشی‌ها صفحهٔ خودشان را دارند: جدول outbox و relay (Outbox)، capture از روی log (Change Data Capture)، event store و replay (Event Sourcing & CQRS)، جدول‌های dedup (Idempotent Consumer & Inbox)، نوشتن میان سرویس‌ها (Saga) و خودِ مدل‌های سازگاری (سازگاری نهایی در دیتابیس‌ها، Replication & Failover). اینکه مرز سرویس‌ها کجا کشیده می‌شود در Service Boundaries است؛ اینکه سرویس‌ها چطور هم را صدا می‌زنند (timeout، تلاش دوباره، کلید idempotency) در Service Communication؛ تفاوت event و فرمان و event-carried state transfer در Event-Driven Architecture؛ و نگاشت یک aggregate به جدول، ORM و تراکنش در Data Persistence Design.

مثال جاری همان مثال کل مسیر DDD است: کسب‌وکار سفارش آنلاین و ارسال با contextهای Sales، Fulfilment، Billing، Catalog و Identity. Sales صاحب aggregate به نام Order است. صفحهٔ «سفارش‌های من» مشتری و ابزار پشتیبانی هر دو برای هر سفارش یک سطر می‌خواهند که هم دانستهٔ Sales (مبلغ، اقلام)، هم دانستهٔ Fulfilment (ارسال‌شده، شرکت حمل، کد رهگیری) و هم دانستهٔ Billing (پرداخت‌شده) را نشان دهد. این سطر read model به نام OrderSummary است که با OrderPlaced از Sales، ParcelDispatched از Fulfilment و InvoicePaid از Billing پر می‌شود.

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

دنبال چه هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
چرا «فقط join بزن» دیگر جواب نمی‌دهدچرا الگوهای داده لازم‌اند
از Meyer 1988 تا Young 2010 تا microservices.ioاز کجا آمده
نه join، نه تراکنش توزیع‌شدهمسئلهٔ داده
یک دیتابیس برای همهٔ سرویس‌ها و اینکه کِی قابل‌تحمل استShared database
instance، schema یا جدول خصوصی؛ polyglot persistenceDatabase per service
فرمان چیزی برنمی‌گرداند، پرس‌وجو چیزی را عوض نمی‌کندCQS
مدل نوشتن و خواندن جدا؛ طیفCQRS
projection: برای هر صفحه، قابل بازسازی، idempotentRead model و projection
replica، logical replication، CDC، event، materialized viewگزینه‌های رساندن داده به سمت خواندن
هنگام پرس‌وجو از صاحبان بپرسیم یا نسخهٔ خودمان را نگه داریمAPI composition در برابر read model
«سفارش دادم و در فهرستم نیست»Read-your-writes
فهرست کهنه، حذف شبح‌وار، والد گم‌شدهخرابی‌های سازگاری نهایی
مالی همه‌چیز را می‌خواهدگزارش‌گیری و تحلیل
فرمان به‌عنوان نیت، نه PUTUI مبتنی بر وظیفه
event به‌عنوان مدل نوشتنEvent sourcing به‌عنوان گزینه
replay fixture، snapshot test، metric تأخیرتست، پایش
schema، الگوریتم، بازسازی، تنظیمات، خطاها، محصولاتسازوکار
کد کاملGo، Laravel
شش مسئلهٔ کلاسیکحل مسئله‌های کلاسیک
کدام الگو برای کدام پرس‌وجوانتخاب
از monolith تا دادهٔ توزیع‌شدهدر معماری
تمرین عملیآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

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

اصطلاحبه زبان سادهمثال کوچکبدون آن چه خراب می‌شود
دیتابیس مشترک (Shared database)چند سرویس جدول‌های یکسانی را می‌خوانند و می‌نویسندSales و Billing هر دو UPDATE orders می‌زنندهیچ‌کس نمی‌تواند تنهایی ستونی را عوض کند؛ قفل‌ها از مرز تیم‌ها رد می‌شوند
دیتابیس برای هر سرویس (Database per service)دادهٔ هر سرویس خصوصی است و فقط از API یا eventهایش در دسترس استجدول invoices در Billing یک نویسنده دارد و هیچ خوانندهٔ بیرونیوابستگی پنهان از راه جدول‌ها
CQSمتد یا وضعیت را عوض می‌کند یا داده برمی‌گرداند، نه هر دوDispatch() error و Status() Statusخواندنی با اثر جانبی؛ «فقط نگاه کردن» داده را عوض می‌کند
CQRSشیء (بعد مدل، بعد انبار) جدا برای نوشتن و خواندنPlaceOrderHandler در برابر OrderSummaryیک مدل که هم برای صفحه و هم برای قاعده کج می‌شود
Read modelنسخه‌ای که برای یک صفحه یا پرس‌وجو شکل گرفتهorder_summary: یک سطر برای هر سفارشN تا join یا N تا فراخوانی سرویس برای هر صفحه
Projection / projectorکدی که eventها را به سطرهای read model تبدیل می‌کندParcelDispatched ستون‌های dispatched_at و carrier را پر می‌کندread model از واقعیت‌ها فاصله می‌گیرد
تأخیر projection (Projection lag)read model چقدر از سمت نوشتن عقب استسفارش ۳۰۰ میلی‌ثانیه پیش ثبت شده و هنوز در فهرست نیستکاربر کار را تکرار می‌کند؛ تیکت پشتیبانی
Read-your-writesبعد از تغییر من، خواندن بعدی من آن را نشان دهدversion: 1 برگردان؛ با min_version=1 بخوان«سفارشم ثبت شد یا نه؟»
API compositionاز صاحبان بپرس و در حافظه join کنBFF اول Sales و بعد Fulfilment را صدا می‌زندصفحه‌های کند و شکننده برای joinهای بزرگ

طیف CQS → CQRS (تصویرش در CQRS):

قدمچه چیزی جدا می‌شودانبارسازگاری خواندنهزینه
1 CQSمتدهایک مدل، یک دیتابیسفوریرایگان: یک قاعدهٔ کدنویسی
2 CQRS با دو شیءسرویس فرمان در برابر سرویس پرس‌وجوهمان جدول‌ها، thin read layerفوریکم
3 جدول خواندنی، همان دیتابیسschema خواندنهمان دیتابیس، projection در همان تراکنشفورینوشتن کندتر
4 انبار خواندنی جدامحل ذخیرهٔ خواندندیتابیس، index یا cache دیگر، projector ناهم‌زماننهایی (با تأخیر)projector، replay، پایش تأخیر
5 سمت نوشتن event-sourcedمحل ذخیرهٔ نوشتن همevent store به‌اضافهٔ projectionهانهایی برای خواندنبیشترین؛ مهارت تازه

راه‌های رساندن داده به سمت خواندن (مقایسه در گزینه‌های رساندن داده):

گزینهمالکیت رعایت می‌شود؟تأخیر معمولشکل نسخه
Read replica از دیتابیس صاحبفقط اگر replica مال خود صاحب باشدمیلی‌ثانیه تا ثانیههمان schema صاحب
Logical replication جدول‌های انتخابیبله، اگر صاحب یک جدول مستند منتشر کندمیلی‌ثانیه تا ثانیهجدول، ستون و سطرهای انتخابی
CDC (Debezium) به انبار خواندنبله، از راه outbox یا جدول منتشرشدهمیلی‌ثانیه تا ثانیهeventهای تغییر سطر که consumer شکلشان را عوض می‌کند
Projection مبتنی بر eventبله: eventها قرارداد هستندمیلی‌ثانیه تا ثانیههر شکلی که صفحه لازم دارد
Materialized viewفقط درون یک دیتابیس (modular monolith)تا REFRESH بعدینتیجهٔ یک query که مثل جدول ذخیره شده

چرا الگوهای داده لازم‌اند ​

درون یک دیتابیس، صفحه‌ای که سفارش، ارسال و فاکتور را با هم می‌خواهد یک JOIN سه‌طرفه است و تغییری که به دو تا از آن‌ها دست می‌زند یک تراکنش. سیستم را به سرویس‌هایی بشکنید که هرکدام صاحب دادهٔ خودشان‌اند و هر دو ابزار از دست می‌رود: Sales نمی‌تواند JOIN fulfilment.shipments بزند مگر جدول خصوصی سرویس دیگری را بخواند، و نمی‌تواند تغییری را در Billing COMMIT کند. صفحهٔ Database per Service از Richardson دقیقاً همین‌ها را عیب می‌شمارد: "Implementing business transactions that span multiple services is not straightforward" و "Implementing queries that join data that is now in multiple databases is challenging." نوشتن میان سرویس‌ها کار saga است (Saga). این فصل بیشتر دربارهٔ نیمهٔ دیگر است: خواندن‌هایی که از چند صاحب عبور می‌کنند، و رابطهٔ سمت نوشتن و سمت خواندن درون یک context (یعنی CQS و CQRS).

یک مدل و یک دیتابیس نگه داریمسمت نوشتن و خواندن را جدا کنیم
هر خواندن تازه استخواندن ممکن است از نوشتن عقب باشد
یک مدل باید هم قاعده‌ها را و هم صفحه‌ها را راضی کندمدل نوشتن فقط از قاعده‌ها محافظت می‌کند؛ read modelها فقط به صفحه‌ها خدمت می‌کنند
join میان contextها به جدول‌های دیگران سرک می‌کشدهر read model نسخهٔ خودش را دارد که با event پر می‌شود
ساختن، تست و رفع اشکال سادهprojector، replay، metric تأخیر، ابزار بازسازی
برای بیشتر contextهای CRUD‌شکل مناسب استبرای چند context با خواندن سنگین و متنوع یا قاعده‌های پیچیده

تمثیلی که در کل صفحه به آن برمی‌گردیم: بیمارستان. هر بخش پروندهٔ خودش را دارد: داروخانه دفتر تحویل دارو، آزمایشگاه نتیجه‌ها، بخش بستری پروندهٔ بیماران. هیچ‌کس از آزمایشگاه در دفتر داروخانه نمی‌نویسد (database per service). پزشک بخش برای هر بیمار به سه بخش سر نمی‌زند (API composition)؛ پرستار پشت میز بخش یک تخته‌وایت‌برد دارد با یک خط برای هر بیمار که هر بار بخشی نتیجه‌ای را تلفنی خبر می‌دهد به‌روز می‌شود (projection به یک read model). تخته ممکن است چند دقیقه عقب باشد و می‌شود پاکش کرد و از روی دفتر تماس‌ها دوباره نوشتش (rebuild). حقیقت را پرونده‌های بخش‌ها تعیین می‌کنند؛ تخته فقط برای نگاه کردن است.

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

  1. «CQRS یعنی دو دیتابیس و Kafka.» Greg Young می‌گوید: "CQRS is simply the creation of two objects where there was previously only one." انبارهای جدا، eventها و سازگاری نهایی گزینه‌هایی دور این الگو هستند، نه خود الگو.
  2. «Database per service یعنی برای هر سرویس یک سرور دیتابیس.» Richardson سه حالت می‌شمارد: جدول خصوصی برای هر سرویس، schema برای هر سرویس، و سرور دیتابیس برای هر سرویس؛ دوتای اول "have the lowest overhead". قاعده خصوصی بودن است، نه جدا بودن فیزیکی.
  3. «Read model همان cache است.» cache بر اساس تقاضا از همان مدل پر می‌شود و منقضی می‌شود. read model شکل دیگر و denormalised است، با event پر می‌شود، مال خواننده است و از روی یک log قابل بازسازی است؛ نه منقضی می‌شود و نه read-through است.

از کجا آمده ​

Meyer، ۱۹۸۸. کتاب Object-Oriented Software Construction از Bertrand Meyer جداسازی فرمان و پرس‌وجو (Command-Query Separation) را معرفی کرد. ما خود کتاب را نخوانده‌ایم؛ اصل را از خلاصهٔ Fowler در ۲۰۰۵ می‌آوریم: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." Fowler استثنایی را هم نگه می‌دارد: "Popping a stack is a good example of a query that modifies state."

دیتابیس گزارش (Reporting database). یادداشت ReportingDatabase از Fowler (تاریخ ۲ آوریل ۲۰۱۴ روی bliki) ایدهٔ قدیمی‌تری را شرح می‌دهد: گزارش‌گیری سنگین سزاوار "a completely different database to the operational database" است و "You don't need to normalize a reporting database, because it's read-only."

Young، ۲۰۱۰. CQRS Documents از Greg Young (PDF، سایت cqrsinfo.com) و نوشتهٔ فوریهٔ ۲۰۱۰ او با عنوان CQRS, Task Based UIs, Event Sourcing agh! به Command and Query Responsibility Segregation نام دادند. اسناد ریشه را به Meyer می‌رسانند و توضیح می‌دهند چرا یک مدل کم می‌آورد: "It is not possible to create an optimal solution for searching, reporting, and processing transactions utilizing a single model." آن نوشته تعریف را عمداً باریک می‌کند: "CQRS is not eventual consistency, it is not eventing, it is not messaging, it is not having separated models for reading and writing, nor is it using event sourcing."

Fowler، ۲۰۱۱. یادداشت CQRS در bliki (۱۴ ژوئیهٔ ۲۰۱۱) تعریف رایج و هشدار را داد: "In particular CQRS should only be used on specific portions of a system (a BoundedContext in DDD lingo) and not the system as a whole."

Vernon، ۲۰۱۳؛ Khononov، ۲۰۲۱. کتاب Implementing Domain-Driven Design از Vaughn Vernon در فصل ۴ (معماری) CQRS را کنار معماری event-محور و event sourcing بررسی می‌کند؛ Learning Domain-Driven Design از Vlad Khononov CQRS را میان الگوهای معماری می‌گذارد و آن را با polyglot persistence (چند انبار خواندن برای یک مدل نوشتن) جفت می‌کند. متن کتاب‌ها را در دست نداشتیم؛ جایگاهشان را خلاصه کرده‌ایم، نه جمله‌هایشان را.

microservices.io. کاتالوگ Chris Richardson الگوهای داده را هستهٔ میکروسرویس‌ها کرد: Database per Service، Shared Database، API Composition، CQRS ("Define a view database, which is a read-only ‘replica’ that is designed specifically to support that query")، Event Sourcing و Saga.

Change data capture و logical replication. PostgreSQL قابلیت توکار "Logical replication using publish/subscribe" را در نسخهٔ ۱۰ اضافه کرد (تاریخ انتشار در یادداشت‌های انتشار: 2017-10-05)؛ Debezium هم log دیتابیس را به جریانی از eventهای تغییر سطر برای Kafka Connect تبدیل کرد. هر دو راه استاندارد پر کردن انبارهای خواندن بدون event دست‌نویس شدند (صفحه‌های PostgreSQL که نقل می‌کنیم مستندات فعلی، یعنی نسخهٔ ۱۹، هستند).

text
     Year   Idea                                        What it changed for reads
1    1988   Meyer: command-query separation              Methods either change or answer
2    2005   Fowler's CQS summary, pop() exception        The rule meets practice
3    2010   Young: CQRS, task-based UI, thin read layer  Two objects, then two models
4    2011   Fowler: CQRS, "specific portions" only       CQRS is per bounded context
5    2013   Vernon IDDD ch. 4                            CQRS inside DDD architecture
6    2014+  microservices.io data patterns               View databases fed by events
7    2017   PostgreSQL 10 logical replication           Table-level copies across DBs
8    later  Debezium CDC on Kafka Connect                The log becomes an event stream

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

هر بلوک یک ترتیب ثابت دارد: به زبان ساده، بدفهمی رایج، تعریف، خط زمانی، سناریوی واقعی، مقایسه، و روش انجامش در SQL و Go و Laravel. کد کامل در Go و Laravel است.

مسئلهٔ داده در میکروسرویس‌ها حیاتی ​

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

بدفهمی رایج: «سرویس دیگر را وسط تراکنش خودمان صدا می‌زنیم.» فراخوانی راه دور درون BEGIN … COMMIT جزو تراکنش نیست: اگر commit بعد از موفقیت فراخوانی شکست بخورد، سرویس دیگر کارش را کرده است، و تا منتظرش هستید قفل‌ها را نگه داشته‌اید.

تعریف: با دادهٔ خصوصی برای هر سرویس، (۱) پرس‌وجوهایی که از چند صاحب داده می‌خواهند باید با API composition یا read model پیاده شوند، و (۲) تراکنش‌های کسب‌وکاری که چند صاحب را تغییر می‌دهند باید sagaیی از تراکنش‌های محلی با جبران‌کننده باشند. از commit دومرحله‌ای (2PC) میان سرویس‌ها پرهیز می‌شود؛ Richardson می‌نویسد: "Distributed transactions are best avoided because of the CAP theorem. Moreover, many modern (NoSQL) databases don’t support them."

text
     Monolith (one DB)                                   Services (three DBs)
1    SELECT o.*, s.carrier, i.paid_at                     Sales DB has orders, Fulfilment DB shipments,
2      FROM orders o JOIN shipments s ... JOIN invoices i   Billing DB invoices: no JOIN reaches all three
3    BEGIN; UPDATE orders ...; UPDATE invoices ...; COMMIT;  Sales COMMIT; publish OrderPlaced -> Billing COMMIT later
4    -> one answer, one atomic change                     -> compose or project; saga; eventual consistency

سناریوی واقعی: فهرست «سفارش‌های من» (داده از Sales، Fulfilment و Billing)؛ جست‌وجوی پشتیبانی با کد رهگیری (دادهٔ Fulfilment، نمایش Sales)؛ «سفارش را لغو کن و پول را برگردان» (نوشتن در Sales و Billing)؛ گزارش پایان ماه مالی (همه‌چیز).

نیازدر monolithمیان سرویس‌هاالگو در این صفحه یا صفحهٔ همسایه
join برای یک رکوردJOINهر صاحب را صدا بزن، در حافظه join کنAPI composition
join، فیلتر، مرتب‌سازی، صفحه‌بندی رکوردهای زیادJOIN … WHERE … ORDER BY … LIMITنسخهٔ محلی که برای همان پرس‌وجو شکل گرفتهRead model
تغییر اتمی دو صاحبیک تراکنشsaga از تراکنش‌های محلیSaga
انتشار مطمئن یک تغییرلازم نیستoutbox در همان تراکنش محلیOutbox
تحلیل روی همه‌چیزگزارش روی دیتابیس OLTP (همین الان هم بد است)انبار داده (warehouse) با CDC یا batchگزارش‌گیری

راه‌حل / نحوهٔ استفاده: این دو قاعده را زود بپذیرید. در Go و Laravel این به یک قاعدهٔ code review تبدیل می‌شود: repository یا مدل Eloquent فقط به جدول‌های context خودش دست می‌زند و هر SQLی که نام schema یک context دیگر را بیاورد رد می‌شود (فصل مالکیت داده این را با roleهای دیتابیس اجبار می‌کند).

sql
-- The query that must disappear from Sales' code once the contexts are split:
SELECT o.id, o.total_minor, s.carrier, i.paid_at
FROM sales.orders o
LEFT JOIN fulfilment.shipments s ON s.order_id = o.id   -- Fulfilment's private table
LEFT JOIN billing.invoices    i ON i.order_id = o.id   -- Billing's private table
WHERE o.customer_id = $1;

دیتابیس مشترک (Shared database) حیاتی ​

به زبان ساده: چند سرویس جدول‌های یکسانی را می‌خوانند و می‌نویسند؛ دیتابیس join و تراکنش را برایشان انجام می‌دهد و در عوض هر جدول به قراردادی تبدیل می‌شود که صاحب ندارد.

بدفهمی رایج: «تا وقتی هر سرویس فقط جدول دیگری را بخواند مشکلی نیست.» خواندن هم وابستگی می‌آورد: وقتی صاحب ستونی را تغییر نام می‌دهد خواننده می‌شکند، و یک query گزارشی طولانی می‌تواند قفل نگه دارد یا جدول صاحب را پف کند (bloat).

تعریف: الگوی Shared database از Richardson: "Each service freely accesses data owned by other services using local ACID transactions." مزیت: "A developer uses familiar and straightforward ACID transactions to enforce data consistency." عیب‌ها: "Development time coupling - a developer working on, for example, the OrderService will need to coordinate schema changes with the developers of other services that access the same tables" و "Runtime coupling - because all services access the same database they can potentially interfere with one another."

text
     Sales service                              Billing service (same database)
1    ALTER TABLE orders RENAME total TO total_minor;   -- deployed Tuesday 10:00
2                                               SELECT total FROM orders WHERE id = $1;
3                                               ERROR: column "total" does not exist   -- invoices stop
4    Monthly report in Billing: SELECT ... FROM orders (12 min, long snapshot)
5    UPDATE orders SET status = 'paid' ...      -- waits / dead tuples pile up behind the report

سناریوی واقعی: ستونی که تغییر نام داده و job شبانهٔ تیم دیگر را می‌شکند؛ دو سرویس که هر دو orders.status را با دو معنای متفاوت می‌نویسند؛ query گزارشی که checkout را کند می‌کند؛ migrationی که سه تیم را در یک جلسه می‌نشاند.

کاربرد دیتابیس مشترکقابل‌قبول؟شرط
دو سرویس روی یک جدول می‌نویسندنهیک صاحب انتخاب کنید (نویسندهٔ واحد)
خواندن جدول‌های درونی سرویس دیگرنهاز API، eventها یا جدول منتشرشده‌اش استفاده کنید
یک سرور فیزیکی، schema و credential جدابلهاین همان database per service با سربار کم است
گذرا: monolith هنوز می‌نویسد و سرویس تازه از viewی می‌خواند که مال monolith استبله، موقتبرنامهٔ حذف تاریخ‌دار؛ view یک قرارداد است
گذرا: یک «جدول یکپارچه‌سازی» منتشرشده و فقط-درج که replicate یا با CDC گرفته می‌شودبلهschema مستند، نسخه‌دار مثل یک event
modular monolith با schemaهای متعلق به ماژول‌هابلهماژول‌ها هرگز به جدول هم دست نمی‌زنند

راه‌حل / نحوهٔ استفاده: اگر در مهاجرت مجبور به اشتراک هستید، قرارداد را به اشتراک بگذارید نه جدول را: یک view یا جدول فقط-درج که صاحب نگهش می‌دارد و roleی آن را می‌خواند که به هیچ چیز دیگری دسترسی ندارد (جزئیات و حرکت‌های brownfield در مالکیت داده).

sql
-- Owner-maintained contract: Billing reads this view, never sales.orders.
CREATE VIEW sales_public.orders_v1 AS
SELECT id AS order_id, customer_id, total_minor, currency, placed_at FROM sales.orders;
GRANT SELECT ON sales_public.orders_v1 TO billing_reader;

دیتابیس برای هر سرویس (Database per service) حیاتی ​

به زبان ساده: دادهٔ هر سرویس خصوصی است؛ دیگران فقط از راه API یا eventهای منتشرشدهٔ آن سرویس به آن می‌رسند. «دیتابیس» یعنی «مجموعه داده‌ای که فقط این سرویس اجازهٔ دست زدن به آن را دارد»، نه لزوماً یک سرور جدا.

بدفهمی رایج: «database per service اجرای دو سرویس روی یک سرور PostgreSQL را ممنوع می‌کند.» Richardson: "You do not need to provision a database server for each service." ممنوع این است که سرویس دیگری دستش را در جدول‌ها کند.

تعریف: "Keep each microservice’s persistent data private to that service and accessible only via its API. A service’s transactions only involve its database." سه درجهٔ جداسازی، همه از صفحهٔ الگو: "Private-tables-per-service – each service owns a set of tables that must only be accessed by that service"، "Schema-per-service – each service has a database schema that’s private to that service" و "Database-server-per-service – each service has it’s own database server." دوتای اول "have the lowest overhead" و schema برای هر سرویس "makes ownership clearer". دادهٔ خصوصی راه ماندگاری چندزبانه (Polyglot persistence) را هم باز می‌کند: هر سرویس انباری را برمی‌دارد که به الگوی دسترسی‌اش می‌خورد (صفحه MongoDB را برای "complex, unstructured data" و Neo4J را برای دادهٔ گرافی مثال می‌زند).

text
     Granularity            What is separate                 Enforcement
1    private tables          naming convention only           code review, architecture tests
2    schema per service      schema + role + credentials      GRANT/REVOKE: other roles get "permission denied"
3    server per service      instance, backups, scaling       network + credentials
-> each step up costs more to run and removes one more way to cheat

سناریوی واقعی: Sales و Billing به‌صورت دو schema روی یک PostgreSQL مدیریت‌شده (ارزان، مالکیت روشن)؛ Catalog که به سرور خودش رفته چون ترافیک جست‌وجو از همه بیشتر است؛ بهینه‌ساز مسیر Fulfilment با انبار گرافی؛ سمت خواندن OrderSummary که برای جدول از PostgreSQL و برای جست‌وجوی متنی از یک موتور جست‌وجو استفاده می‌کند (polyglot persistence در سمت خواندن).

درجههزینهجداسازی بارجلوی SQL میان‌سرویسی را می‌گیرد؟مناسب برای
جدول خصوصیکمتریننداردنه (قرارداد)modular monolith، سرویس‌های اولیه
schema برای هر سرویسکمندارد (همان instance)بله، با roleهاپیش‌فرض بیشتر تیم‌ها
دیتابیس منطقی برای هر سرویسکم تا متوسطندارد (همان instance)بله (\c لازم است)جداسازی قوی، همان عملیات
سرور برای هر سرویسبیشترینکاملبلهthroughput خیلی بالا، موتورهای متفاوت

راه‌حل / نحوهٔ استفاده: برای هر context یک schema و یک login role که search_path آن روی schema خودش باشد، به‌اضافهٔ تستی که اگر SQL یک context نام schema دیگری را بیاورد شکست بخورد.

sql
CREATE SCHEMA sales;   CREATE ROLE sales_svc LOGIN;   GRANT USAGE, CREATE ON SCHEMA sales TO sales_svc;
CREATE SCHEMA billing; CREATE ROLE billing_svc LOGIN; GRANT USAGE, CREATE ON SCHEMA billing TO billing_svc;
ALTER ROLE sales_svc SET search_path = sales;
-- billing_svc: SELECT * FROM sales.orders;  -> ERROR: permission denied for schema sales (SQLSTATE 42501)
php
// config/database.php: one connection per owner (Laravel). Sales models use 'sales'.
'sales'      => [...$pg, 'search_path' => 'sales',      'username' => env('SALES_DB_USER')],
'read_model' => [...$pg, 'search_path' => 'read_model', 'username' => env('READ_DB_USER')],

CQS: فرمان و پرس‌وجو در سطح متد حیاتی ​

به زبان ساده: هر متد یا کاری انجام می‌دهد (فرمان، Command) یا چیزی به شما می‌گوید (پرس‌وجو، Query)، نه هر دو. پرسیدن یک سؤال نباید جوابش را عوض کند.

بدفهمی رایج: «فرمان باید void برگرداند، پس برگرداندن error یا شناسه CQS را می‌شکند.» در خلاصهٔ Fowler فرمان‌ها "do not return a value"، اما نکتهٔ اصلی وضعیت قابل‌مشاهده است: برگرداندن شکست (error در Go یا exception در PHP) هیچ داده‌ای دربارهٔ شیء حمل نمی‌کند. برگرداندن version تازه به‌عنوان توکن سازگاری انحرافی عمل‌گرایانه و رایج است؛ جایی که CQS واقعاً از دست می‌رود برگرداندن کل رکورد به‌روزشده است.

تعریف: جداسازی فرمان و پرس‌وجو از Meyer، به خلاصهٔ Fowler: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." اسناد Young خوانش CQRS را اضافه می‌کنند: "If you have a return value you cannot mutate state. If you mutate state your return type must be void." استثناهای شناخته‌شده: pop()، متد next() در iteratorها، عملیات اتمی «از صف بردار و برگردان».

text
     Caller                             Order (CQS)                             Order (violates CQS)
1    o.CanDispatch()                    -> true, nothing changed                NextShipmentAndMark() -> "o-1", status=picking
2    o.CanDispatch()  (dashboard poll)  -> true, nothing changed                NextShipmentAndMark() -> "o-2", status=picking
3    o.Dispatch()                       -> nil, status=dispatched, version 3   the dashboard "looked" and moved two orders

سناریوی واقعی: داشبوردی که «سفارش بعدی برای جمع‌آوری» را poll می‌کند و در همان حال سفارش‌ها را جابه‌جا می‌کند؛ getterی که مبلغ را تنبلانه حساب و ذخیره می‌کند؛ accessor در Eloquent که می‌نویسد؛ find() در repository که ستون «آخرین بازدید» را روی aggregate بالا می‌برد (آن را به یک event یا فرمان جدا ببرید).

شکل متدCQS؟توضیح
func (o *Order) Dispatch() errorبلهفرمان؛ error وضعیت نیست
func (o *Order) Status() Statusبلهپرس‌وجو؛ هر جا و به هر ترتیبی امن است
func (h Handler) Handle(cmd) (Ack, error) با Ack{Version}عمل‌گرایانهتوکن برای read-your-writes، بدون دادهٔ خواندنی
public function dispatch(): Order که $this برمی‌گرداندخاکستریسبک fluent؛ اگر چیز دیگری برنگرداند اشکالی ندارد
UPDATE … RETURNING * پشت متدی به اسم «بعدی را بده»نهپرس‌وجو با اثر جانبی
Stack.pop()نه، پذیرفته‌شدهFowler: "I'm prepared to break it to get my pop"

راه‌حل / نحوهٔ استفاده: در مدل domain فرمان‌ها فقط error (Go) یا void همراه exception (PHP) برگردانند؛ پرس‌وجوها بی‌اثر جانبی باشند؛ «از صف بردار و علامت بزن» را به فرمانی با نام صریح منتقل کنید.

go
func (o *Order) Dispatch() error {        // COMMAND
	if o.status != Paid {
		return ErrNotPaid
	}
	o.status, o.version = Dispatched, o.version+1
	return nil
}
func (o *Order) CanDispatch() bool { return o.status == Paid } // QUERY
php
public function dispatch(): void            // command
{
    if (! $this->canDispatch()) {
        throw new DomainException('An unpaid order cannot be dispatched.');
    }
    $this->status = 'dispatched';
    $this->version++;
}

public function canDispatch(): bool { return $this->status === 'paid'; } // query

CQRS: مدل نوشتن و مدل خواندن جدا حیاتی ​

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

بدفهمی رایج: «CQRS به event sourcing، message broker و سازگاری نهایی نیاز دارد.» Young: "CQRS is not eventual consistency, it is not eventing, it is not messaging, it is not having separated models for reading and writing, nor is it using event sourcing." هرکدام از این‌ها تصمیم جدایی است که بعد از جدا کردن ممکن است بگیرید.

تعریف: Young: "CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query." مثال او CustomerService را به CustomerWriteService و CustomerReadService می‌شکند. Fowler شکل کامل را توصیف می‌کند: "split that conceptual model into separate models for update and display"، و "The in-memory models may share the same database, in which case the database acts as the communication between the two models. However they may also use separate databases, effectively making the query-side's database into a real-time ReportingDatabase." سمت فرمان مدل domain و aggregateها را نگه می‌دارد؛ سمت پرس‌وجو به لایهٔ خواندن نازک (Thin read layer) تبدیل می‌شود که به گفتهٔ Young "reads directly from the database and projects DTOs".

more read independence, read scale, per-screen modelsless machinery, no lag, one model to understand1 CQSmethods are eithercommand or queryDispatch() errorStatus() Status2 CQRS: two objectsOrderCommandsOrderQueriessame tables,thin read layerno lag3 read tablessame databaseprojection in thesame transaction(synchronous)no lag, slower writes4 read storeseparate database,index or cacheprojector fed byevents or CDC(asynchronous)lag: ms to secondsrebuildable, versioned5 event-sourcedwrite sideevents are thesource of truthevery read isa projectionreplay from day one,steep learning curveFowler: use CQRS on specific bounded contexts only; stop at the leftmost step that solves the problem

تصویر همان طیف جدول یک‌دقیقه‌ای است: هر قدم به راست یک چیز دیگر را جدا می‌کند و یک تکهٔ دیگر سازوکار هزینه دارد. قدم‌های ۱ تا ۳ خواندن را فوراً سازگار نگه می‌دارند؛ قدم ۴ تأخیر می‌آورد؛ قدم ۵ سمت نوشتن را هم عوض می‌کند.

projection هم‌زمان در برابر ناهم‌زمان. در قدم ۳ جدول خواندنی در همان تراکنش aggregate به‌روز می‌شود: تأخیری نیست، اما هر نوشتن هزینهٔ همهٔ read modelها را می‌دهد و read model فقط می‌تواند در همان دیتابیس باشد. در قدم ۴ یک projector انبار خواندن را بعد از commit و از روی eventها (یا CDC) به‌روز می‌کند: نوشتن سریع می‌ماند و انبار خواندن هر چیزی می‌تواند باشد، اما خواندن عقب می‌افتد.

text
     Synchronous (step 3)                              Asynchronous (step 4)
1    BEGIN                                             BEGIN
2    UPDATE sales.orders SET ... version = 2           UPDATE sales.orders SET ... version = 2
3    UPDATE read.order_summary SET ... (same tx)       INSERT INTO sales_outbox (OrderPaid ...)
4    COMMIT  -> list shows the change at once           COMMIT  -> 202 {version: 2}
5                                                       relay -> broker -> projector (50-500 ms)
6                                                       UPDATE order_summary ... -> list shows it now

کِی نمی‌ارزد. Fowler: "Many systems do fit a CRUD mental model, and so should be done in that style." و "Usually there's enough overlap between the command and query sides that sharing a model is easier. Using CQRS on a domain that doesn't match it will add complexity, thus reducing productivity and increasing risk." او سود را در دو جهت می‌بیند: domainهای پیچیده، و "high performance applications" با بار خواندن و نوشتن بسیار متفاوت؛ و اگر فقط چند پرس‌وجو سنگین‌اند، "you can still use a ReportingDatabase".

سناریوی واقعی: صفحهٔ سفارش Sales داده از سه context و صفحه‌بندی بر اساس تاریخ می‌خواهد (قدم ۴ موجه است)؛ مدیریت کاربران در Identity یک CRUD است (قدم ۱ کافی است)؛ جست‌وجوی Catalog موتور جست‌وجو می‌خواهد (قدم ۴ به یک search index)؛ دفتر کلی که حسابرس‌ها تاریخچهٔ هر تغییرش را می‌خواهند (قدم ۵ شاید موجه باشد، event sourcing را ببینید).

context در مثال جارینیاز خواندنقدم انتخاب‌شدهچرا
Identity (کاربران، نقش‌ها)فهرست‌های مدیریتی1 (فقط CQS)CRUD‌شکل؛ هشدار Fowler صدق می‌کند
Catalog (محصولات)جست‌وجوی متنی، facet4: search index که با event پر می‌شودموتور جست‌وجو به چیزی جواب می‌دهد که SQL نمی‌دهد
Sales (سفارش‌ها)«سفارش‌های من» با واقعیت‌های Fulfilment و Billing4: read model به نام OrderSummaryدادهٔ چندصاحبه، صفحه‌بندی، نسبت خواندن بالا
Billing (فاکتور، پرداخت)ردپای حسابرسی، صورت‌حساب2 یا 3؛ 5 فقط اگر حسابرسی بخواهدسازگاری قوی از مقیاس خواندن مهم‌تر است
Fulfilment (ارسال‌ها)فهرست جمع‌آوری انبار3: جدول خواندنی در همان دیتابیسدادهٔ تازه لازم است، یک صاحب

راه‌حل / نحوهٔ استفاده: اول سرویس اپلیکیشن را بشکنید (قدم ۲): فرمان‌ها از handlerهایی می‌گذرند که aggregate بار می‌کنند؛ پرس‌وجوها از یک سرویس خواندن می‌گذرند که SQL اجرا می‌کند و DTO برمی‌گرداند، هرگز aggregate. فقط وقتی نیاز اندازه‌گیری‌شده‌ای پیدا شد به راست بروید.

go
// Step 2 in Go: two objects over the same tables.
type OrderCommands struct{ Repo sales.Repository }                  // Place, Pay, Ship
type OrderQueries struct{ DB *pgxpool.Pool }                          // thin read layer
func (q OrderQueries) ByCustomer(ctx context.Context, customerID string) ([]OrderRow, error) { /* SELECT ... */ return nil, nil }
php
// Step 2 in Laravel: an action for each command, a query class for reads.
final class PlaceOrderAction { public function __invoke(PlaceOrder $cmd): int { /* ... */ } }
final class OrderQueries { public function byCustomer(string $id): Collection { return DB::table('order_summary')->where('customer_id', $id)->get(); } }

Read model و projection حیاتی ​

به زبان ساده: read model جدولی (یا index یا سندی) است که برای یک صفحه یا یک خانواده پرس‌وجو ساخته شده؛ یک projector آن را با اعمال eventها یکی‌یکی به‌روز نگه می‌دارد، آن‌قدر امن که تکرار، جابه‌جایی ترتیب و یک بازپخش کامل همه به همان سطرها برسند.

بدفهمی رایج: «read model باید مثل مدل نوشتن نرمال باشد تا قابل استفادهٔ دوباره باشد.» Young: سمت پرس‌وجو "would want data in a denormalized way to minimize the number of joins needed". read modelی که بخواهد به همهٔ صفحه‌ها خدمت کند خودش یک مدل نوشتن دوم می‌شود.

تعریف: read model (view model، query model، projection) نسخه‌ای denormalised و به‌شکل پرس‌وجوست که مال خواننده است. projection تابعی است از جریانی مرتب از eventها به آن نسخه؛ projector (projection handler) کدی است که آن را اجرا می‌کند. ویژگی‌هایی که read model در production لازم دارد:

  • برای هر صفحه یا خانوادهٔ پرس‌وجو: برای «سفارش‌های من» یک سطر برای هر سفارش، نه یک گراف عمومی سفارش.
  • به‌روزرسانی idempotent: تحویل حداقل‌یک‌بار است، پس اعمال دوبارهٔ یک event نباید چیزی را عوض کند؛ ما شناسهٔ event (event id) را در همان تراکنشِ به‌روزرسانی سطر ثبت می‌کنیم.
  • مقاوم در برابر ترتیب: eventهای contextهای مختلف با هر ترتیبی می‌رسند؛ هر event فقط ستون‌های context خودش را می‌نویسد، سطر upsert می‌شود و ستون‌های Sales با version از Sales محافظت می‌شوند.
  • قابل بازسازی (Rebuildable): read model را می‌شود پاک کرد و از روی logی از eventها دوباره ساخت (بازپخش، Replay)؛ projector آن log را (received_events) خودش نگه می‌دارد چون دیتابیس contextهای دیگر مال ما نیست که دوباره بخوانیمش.
  • نسخه‌دار (Versioned): شکل تازه کنار شکل قبلی ساخته می‌شود (order_summary_v2 یا یک جدول rebuild)، عقب‌ماندگی‌اش جبران می‌شود و بعد جایگزین می‌شود.
  • جبران عقب‌ماندگی (Catch-up): projector تازه یا راه‌اندازی‌شده اول کارهای عقب‌افتاده را از آخرین موقعیتش انجام می‌دهد و بعد ترافیک زنده را می‌گیرد.
Sales DBorders (Order aggregate)sales_outboxOrderPlaced v1Fulfilment DBshipmentsfulfilment_outboxParcelDispatched v1Billing DBinvoicesbilling_outboxInvoicePaid v1brokertopics /queuesat-least-onceread-side service (owns its own store)OrderSummary projectordecode, dedup by event id,upsert own columns onlyreceived_eventsUNIQUE event_id= dedup + replay logorder_summary1 row per order, per screensearch projector-> search index (Scout)query APIGET ?min_version=nrebuildreplay log, then swapanalytics: CDC or batch copies into a warehousereports never query the services' production databases

تصویر مثال جاری را نشان می‌دهد: سه صاحب از راه outbox خودشان منتشر می‌کنند، broker حداقل یک‌بار تحویل می‌دهد، projector در یک تراکنش هم received_events (dedup و log بازپخش) و هم order_summary را می‌نویسد، projector دوم search index را پر می‌کند و rebuild هم log را در یک جدول تازه بازپخش می‌کند. تحلیل داده راه جدایی به سمت warehouse دارد.

text
     Delivery (at-least-once, any order)           order_summary row for o-1 after the step
1    fulfilment.parcel.dispatched.v1  evt-ship-1        + {dispatched_at, carrier=DHL}           status=pending
2    fulfilment.parcel.dispatched.v1  evt-ship-1 (dup)  unchanged: event id already in received_events
3    sales.order.placed.v1            evt-placed-1 v1   + {customer, total=2500, sales_version=1} status=dispatched
4    billing.invoice.paid.v1          evt-paid-1        + {paid_at, paid_minor=2500}             status=completed
5    sales.order.placed.v1            evt-placed-0 v0   ignored: sales_version 0 < 1 (stale)
-> same row as if the events had arrived in the "right" order, exactly once

سناریوی واقعی: «سفارش‌های من» (همین صفحه)؛ read model «نمای ۳۶۰ درجهٔ مشتری» برای پشتیبانی که از پنج context پر می‌شود؛ فهرست جمع‌آوری انبار مرتب‌شده بر اساس تاریخ قول‌داده‌شده؛ search index محصول که از eventهای Catalog و Pricing پر می‌شود؛ شمارندهٔ «کل خرید مشتری» (مراقب باشید: شمارنده ذاتاً idempotent نیست و برای همین جدول dedup مهم است).

تکنیک projectionتکرار را تحمل می‌کندجابه‌جایی میان منبع‌هاجابه‌جایی درون یک منبعنکته
UPDATE … WHERE id سادهنهنه (سطر ممکن است هنوز نباشد)نهبی‌صدا ۰ سطر را عوض می‌کند
upsert ستون‌های خودی (ON CONFLICT DO UPDATE)بله برای به‌روزرسانی‌های «set»بلهنهشمارنده‌ها هنوز دوبار می‌شمارند
upsert به‌اضافهٔ version guard (WHERE s.sales_version < EXCLUDED.sales_version)بلهبلهبلهevent باید version داشته باشد
جدول dedup (received_events با event_id یکتا) در همان تراکنشهمیشه بلهبا upsert ترکیب شودبا guard ترکیب شودlog بازپخش هم هست
وضعیت را از واقعیت‌های موجود استخراج کن—بله—ستون «status»ی نیست که بازنویسی شود

راه‌حل / نحوهٔ استفاده: هستهٔ projector در Go؛ کد کامل در Go و listener در Laravel در Laravel است.

go
func (p *Projector) Handle(ctx context.Context, env contracts.Envelope) error {
	patch, err := Decode(env) // unknown types -> nil: forward compatible
	if err != nil || patch == nil {
		return err
	}
	applied, err := p.Store.ApplyOnce(ctx, env, patch) // log + upsert, one transaction
	if err == nil && applied {
		p.Lag.Observe(env.Source, p.Now().Sub(env.Time))
	}
	return err
}
sql
INSERT INTO order_summary AS s (order_id, dispatched_at, carrier, tracking_ref, updated_at)
VALUES ($1, $2, $3, $4, now())
ON CONFLICT (order_id) DO UPDATE SET dispatched_at = EXCLUDED.dispatched_at,
  carrier = EXCLUDED.carrier, tracking_ref = EXCLUDED.tracking_ref, updated_at = now();

گزینه‌های رساندن داده به سمت خواندن (Read-side replication) مهم ​

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

بدفهمی رایج: «read replica همان CQRS است.» replica فیزیکی همان schema دیتابیس اصلی را دارد: خواندن را مقیاس می‌دهد اما نه مدل متفاوتی به شما می‌دهد و نه داده‌ای از صاحبان دیگر. ابزار مقیاس است، با تأخیر خودش (Replication & Failover).

تعریف:

  • Read replica دیتابیس: نسخهٔ بایت‌به‌بایت (فیزیکی) از دیتابیس صاحب، فقط‌خواندنی، با تأخیر میلی‌ثانیه تا ثانیه. همان schema، همان صاحب.
  • Logical replication جدول‌های انتخابی: در PostgreSQL، "method of replicating data objects and their changes, based upon their replication identity (usually a primary key)". یک publication جدول‌ها، ستون‌ها ("Each publication can optionally specify which columns of each table are replicated to subscribers") و سطرها (row filter) را انتخاب می‌کند؛ subscription در سمت گیرنده آن را دریافت می‌کند. "The database schema and DDL commands are not replicated."
  • CDC به انبار خواندن: Debezium از راه logical decoding (plugin.name=pgoutput و wal_level=logical) write-ahead log را می‌خواند و eventهای تغییر سطر (op با مقدارهای c، u، d و r برای خواندن‌های snapshot) را به Kafka می‌فرستد؛ یک consumer آن‌ها را به شکل انبار خواندن درمی‌آورد. مستندات connector مربوط به PostgreSQL در Debezium: در حالت عادی دقیقاً یک‌بار، اما "while it is recovering from the fault, it’s possible that the connector might emit some duplicate change events"، یعنی حداقل یک‌بار.
  • Projection مبتنی بر event: صاحب integration eventها را (از راه outbox) منتشر می‌کند و خواننده آن‌ها را project می‌کند. eventها قراردادهای طراحی‌شده‌اند، نه سطرهای جدول.
  • Materialized view: نتیجهٔ ذخیره‌شدهٔ یک query درون یک دیتابیس که با REFRESH MATERIALIZED VIEW تازه می‌شود؛ گزینهٔ CONCURRENTLY "without locking out concurrent selects" تازه می‌کند اما index یکتا می‌خواهد.
text
     Owner commits at t=0                     When the reader sees it
1    physical replica                          t + replay lag (ms..s), same schema
2    logical replication (selected tables)     t + apply lag (ms..s), selected columns/rows
3    CDC (Debezium -> Kafka -> consumer)       t + poll + Kafka + consumer (100 ms..s)
4    outbox -> broker -> projector             t + relay interval + broker + projector (ms..s)
5    materialized view                         at the next REFRESH (minutes, hours)

سناریوی واقعی: read replica برای صفحه‌های تاریخچهٔ سفارش خود Sales؛ logical replication جدول فقط-درج invoice_payments از Billing به دیتابیس خواندن؛ CDC از جدول محصولات Catalog به search index وقتی Catalog هنوز نمی‌تواند event منتشر کند؛ projection مبتنی بر event برای OrderSummary؛ materialized view برای جدول شبانهٔ «سفارش به تفکیک منطقه» در modular monolith.

گزینهمالکیت رعایت می‌شودتأخیرپیچیدگی اجراشکل نسخه قابل تغییر استjoin میان صاحبانریسک اصلی
Read replicaبله (replica خود صاحب)میلی‌ثانیه تا ثانیهکمنهنهخواندن کهنه بعد از نوشتن
Logical replicationبله، اگر صاحب جدول قراردادی منتشر کندمیلی‌ثانیه تا ثانیهمتوسطفقط ستون و سطربله، در subscriberDDL منتقل نمی‌شود؛ slotها WAL نگه می‌دارند
CDC (Debezium)فقط از راه outbox یا جدول منتشرشده۱۰۰ میلی‌ثانیه تا ثانیهزیاد (Kafka Connect)بله، در consumerبلهخواننده به شکل جدول وابسته می‌شود
Projection مبتنی بر eventبله، eventها قرارداد هستندمیلی‌ثانیه تا ثانیهمتوسطبلهبلهتأخیر، idempotency، منبع replay
Materialized viewفقط درون یک دیتابیستا refreshکمبله (SQL)بله، در یک دیتابیسکهنگی؛ هزینهٔ محاسبهٔ کامل

راه‌حل / نحوهٔ استفاده: برای read modelهای چندصاحبه event را ترجیح دهید؛ logical replication یا CDC را فقط روی جدول‌هایی به کار ببرید که صاحب به‌عنوان قرارداد منتشر می‌کند؛ materialized view را درون دیتابیس یک صاحب (یا یک modular monolith) نگه دارید. SQL دو گزینهٔ A و B:

sql
-- Alternative A (same database, modular monolith): a materialized view over
-- tables owned by three modules. Cheap, but it couples the view to every
-- owner's schema and it is only as fresh as the last refresh.
CREATE MATERIALIZED VIEW reporting.order_summary_mv AS
SELECT o.id AS order_id, o.customer_id, o.total_minor, o.placed_at,
       s.dispatched_at, s.carrier, i.paid_at
FROM sales.orders o
LEFT JOIN fulfilment.shipments s ON s.order_id = o.id
LEFT JOIN billing.invoices    i ON i.order_id = o.id;
CREATE UNIQUE INDEX ON reporting.order_summary_mv (order_id); -- required for CONCURRENTLY
REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.order_summary_mv;

-- Alternative B (separate databases): PostgreSQL logical replication of
-- SELECTED tables, columns and rows into the read database. The owner publishes
-- a deliberately small, documented, insert-only table of facts rather than its
-- internal invoices table. DDL is not replicated: schema changes are a
-- contract change, coordinated like an event version.
-- On the Billing database (publisher, wal_level = logical):
CREATE PUBLICATION billing_payments_pub
  FOR TABLE billing.invoice_payments (payment_id, order_id, invoice_id, paid_minor, paid_at)
  WHERE (paid_minor > 0)                -- row filter: refunds stay private
  WITH (publish = 'insert');            -- insert-only, so the filter may use any column
-- On the read database (subscriber); the target table must already exist there:
CREATE SUBSCRIPTION read_billing_payments
  CONNECTION 'host=billing-db dbname=billing user=replicator'
  PUBLICATION billing_payments_pub;
-- The read side builds order_summary from its own replicated copy; it never
-- connects to Billing's database. The apply worker runs with
-- session_replication_role = replica, so a projection trigger on the
-- subscriber must be enabled with ENABLE ALWAYS (or ENABLE REPLICA):
ALTER TABLE billing.invoice_payments ENABLE ALWAYS TRIGGER project_payment_into_summary;

connector مربوط به Debezium برای همان جدول (JSON مربوط به Kafka Connect؛ publication.autocreate.mode=filtered همان چیزی است که مستندات Debezium همراه pgoutput توصیه می‌کند تا connector سراغ CREATE PUBLICATION … FOR ALL TABLES نرود):

json
{
  "name": "billing-payments-cdc",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "billing-db",
    "database.port": "5432",
    "database.user": "debezium",
    "database.password": "${file:/secrets/billing.properties:password}",
    "database.dbname": "billing",
    "topic.prefix": "billing",
    "plugin.name": "pgoutput",
    "publication.name": "dbz_billing_payments",
    "publication.autocreate.mode": "filtered",
    "table.include.list": "billing.invoice_payments",
    "column.include.list": "billing.invoice_payments.payment_id,billing.invoice_payments.order_id,billing.invoice_payments.invoice_id,billing.invoice_payments.paid_minor,billing.invoice_payments.paid_at",
    "snapshot.mode": "initial",
    "heartbeat.interval.ms": "10000"
  }
}

API composition در برابر read model در CQRS مهم ​

به زبان ساده: برای پرس‌وجویی که از چند صاحب عبور می‌کند یا هنگام درخواست از هر صاحب می‌پرسید و جواب‌ها را به هم می‌دوزید، یا نسخهٔ خودتان را نگه می‌دارید که با eventهای آن‌ها پر می‌شود و فقط از آن می‌پرسید.

بدفهمی رایج: «API composition گزینهٔ خام است و read model گزینهٔ بالغ.» composition تازه‌تر و ساده‌تر است و برای جست‌وجوهای کلیددار کوچک درست است؛ انتخاب اول درست همین است و فصل مالکیت داده این دو را مفصل مقایسه می‌کند.

تعریف: API composition: "Implement a query by defining an API Composer, which invoking the services that own the data and performs an in-memory join of the results"؛ عیب: "Some queries would result in inefficient, in-memory joins of large datasets." read model در CQRS: "Define a view database, which is a read-only ‘replica’ that is designed specifically to support that query" که "by subscribing to Domain events published by the service that own the data" به‌روز می‌ماند؛ عیب: "Replication lag/eventually consistent views".

text
     "My orders, newest first, 20 per page, with shipping and payment state"
     API composition                                   OrderSummary read model
1    Sales: GET /orders?customer=c-9&limit=20  40 ms   SELECT ... FROM order_summary
2    Fulfilment: GET /shipments?orders=...    35 ms      WHERE customer_id = 'c-9'
3    Billing: GET /invoices?orders=...        30 ms      ORDER BY placed_at DESC LIMIT 20   (4 ms)
4    join in memory, ~80 ms; Billing down -> partial   Billing down -> page still works, payment maybe stale
5    filter "unpaid only": Sales cannot page by Billing's state -> read model needed

سناریوی واقعی: صفحهٔ جزئیات سفارش (composition، با یک شناسه)؛ «سفارش‌های من» با فیلترهای چندصاحبه (read model)؛ جست‌وجوی پشتیبانی با کد رهگیری (read model یا search index)؛ خلاصهٔ checkout که باید دقیق باشد (composition از صاحبان، بی‌دادهٔ کهنه).

پرسشAPI compositionRead model
تازگیزندهعقب (میلی‌ثانیه تا ثانیه)
فیلتر/مرتب‌سازی/صفحه‌بندی بر اساس فیلد صاحب دیگرنهبله
وقتی یک صاحب از کار افتاده کار می‌کندناقصبله (کهنه)
اجزای متحرکcomposer، timeout، batchevent، projector، انبار، replay، metric تأخیر
بهترین برایجست‌وجوی کلیددار، join کوچک، جواب دقیقفهرست، جست‌وجو، داشبورد، نسبت خواندن بالا

راه‌حل / نحوهٔ استفاده: با composition شروع کنید؛ فراخوانی‌ها را batch کنید (یکی برای هر صاحب، نه یکی برای هر سطر)؛ پرس‌وجو را وقتی به read model ببرید که فیلتر یا صفحه‌بندی چندصاحبه بخواهد، یا composition هدف تأخیر یا دسترس‌پذیری‌اش را بشکند (SLOها).

go
// Composition in Go: one batched call per owner, a budget for the whole page.
ctx, cancel := context.WithTimeout(ctx, 150*time.Millisecond)
defer cancel()
orders, err := sales.ListByCustomer(ctx, customerID, 20)
ships, _ := fulfilment.ByOrders(ctx, ids(orders)) // degrade: missing -> "unknown"
php
// Composition in Laravel with Http::pool (parallel requests).
[$orders, $ships] = Http::pool(fn ($pool) => [
    $pool->timeout(1)->get('http://sales/orders', ['customer' => $id]),
    $pool->timeout(1)->get('http://fulfilment/shipments', ['customer' => $id]),
]);

خواندنِ نوشتهٔ خود بعد از فرمان (Read-your-writes) حیاتی ​

به زبان ساده: بعد از اینکه سفارش دادم باید آن را ببینم، حتی اگر بقیه یک لحظه بعد ببینند. با read model ناهم‌زمان این خودبه‌خود اتفاق نمی‌افتد؛ باید برایش طراحی کنید.

بدفهمی رایج: «projector را سریع‌تر کنیم، مشکل حل می‌شود.» تأخیر در یک روز آرام ۲۰ میلی‌ثانیه و هنگام حادثهٔ broker یا rebuild ۲۰ ثانیه است؛ درخواست بعدی کاربر اغلب کمتر از ۱۰۰ میلی‌ثانیه بعد از نوشتن می‌رسد. به سازوکار نیاز دارید، نه به امید.

تعریف: read-your-writes یک ضمانت session است: خواندن‌های یک کلاینت نوشته‌های قبلی همان کلاینت را منعکس می‌کنند (مدلش در سازگاری نهایی در دیتابیس‌ها تعریف شده). برای read model در CQRS چهار راهبرد:

  1. توکن نسخه (Version token) و صبر برای projection: فرمان version تازهٔ aggregate را برمی‌گرداند (202 {version: 1})؛ پرس‌وجو min_version=1 را می‌گیرد و در یک بودجهٔ کوتاه صبر می‌کند تا سطر به آن برسد، وگرنه 202 با Retry-After جواب می‌دهد.
  2. خواندن چسبنده (Sticky reads): در یک پنجرهٔ کوتاه بعد از نوشتن، همان کاربر از مدل نوشتن (یا دیتابیس اصلی) جواب می‌گیرد. گزینهٔ sticky در Laravel همین را برای یک درخواست روی اتصال با تفکیک خواندن/نوشتن انجام می‌دهد: "If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection."
  3. خوش‌بینی UI (UI optimism): کلاینت نسخهٔ خودش را فوراً با برچسب «در حال پردازش» نشان می‌دهد و وقتی read model به آن version رسید هماهنگ می‌کند.
  4. projection هم‌زمان برای همین یک read model: قدم ۳ طیف (همان تراکنش)، اگر read model در دیتابیس صاحب باشد.
t0: POST /orders -> 202 {version: 1}~200 ms: projector applies v1timenaive read(no strategy)GET at 50 ms: order missinguser clicks "Buy" againversion tokenwait-for-projectionGET ?min_version=1 polls200 with v1 (or 202 after budget)sticky readwrite model / primarysame user reads the write side for a short windowUI optimismclient keeps its copyrender own copy, "processing"reconcile when v1 arrives

خط زمانی نشان می‌دهد چرا خواندن ساده‌لوحانه شکست می‌خورد: درخواست بعدی کاربر پیش از اینکه projector event را اعمال کند می‌رسد. راهبرد توکن دقیقاً منتظر همان event می‌ماند؛ راهبرد چسبنده از read model دوری می‌کند؛ UI خوش‌بین اصلاً نمی‌پرسد.

text
     Client                         Sales (write)                 Read side
1    POST /orders {order_id: o-1}   BEGIN; insert; outbox; COMMIT
2    <- 202 {version: 1}, Location: /order-summaries/o-1?min_version=1
3    GET .../o-1?min_version=1                                    row missing -> wait (poll 50 ms)
4                                                                  projector applies OrderPlaced v1 (t=180 ms)
5    <- 200 {status: "placed", sales_version: 1}                  (budget 300 ms not exceeded)
6    (if not reached in 300 ms) <- 202 Retry-After: 1             UI keeps its optimistic copy

سناریوی واقعی: «سفارش‌های من» درست بعد از checkout؛ ویرایش پروفایل که در صفحهٔ بعد نمایش داده می‌شود؛ مدیری که محصولی را غیرفعال می‌کند و فهرست را دوباره بار می‌کند؛ پشتیبانی که پول را برمی‌گرداند و نمای مشتری را تازه می‌کند.

راهبردروی چند دستگاه کار می‌کندبار روی سمت نوشتنتجربهٔ کاربرکِی
توکن نسخه + صبربله، اگر توکن همراه کلاینت برود (URL، پاسخ)ندارددر بدترین حالت یک spinner کوتاهپیش‌فرض برای read model ناهم‌زمان
خواندن چسبنده (sticky در Laravel، «۵ ثانیه از primary بخوان»)نه (برای هر درخواست یا session)کمینامرئیreplicaهای با تفکیک خواندن/نوشتن؛ خواندن در همان درخواست
خوش‌بینی UIنه (فقط کلاینتی که عمل کرده)نداردفوریفهرست‌هایی که کاربر همین الان چیزی به آن اضافه کرده
projection هم‌زمانبلههر نوشتن هزینه می‌دهدنامرئیread model در دیتابیس صاحب که باید دقیق باشد

راه‌حل / نحوهٔ استفاده: از فرمان توکن برگردانید و در پرس‌وجو کوتاه صبر کنید.

go
row, err := query.WaitFor(ctx, store, orderID, minVersion, 300*time.Millisecond, 50*time.Millisecond)
if errors.Is(err, query.ErrNotYetProjected) {
	w.Header().Set("Retry-After", "1")
	w.WriteHeader(http.StatusAccepted)
	return
}
php
// config/database.php for a read/write split on the WRITE side's own connection:
'sales' => ['read' => ['host' => ['10.0.0.11']], 'write' => ['host' => ['10.0.0.10']], 'sticky' => true, /* ... */],

خرابی‌های سازگاری نهایی و طراحی دور آن‌ها مهم ​

به زبان ساده: read model ناهم‌زمان گاهی برای مدتی اشتباه است. این خرابی‌ها قابل پیش‌بینی‌اند، پس می‌توانید هر صفحه را طوری طراحی کنید که از آن‌ها جان سالم به در ببرد.

بدفهمی رایج: «سازگاری نهایی (Eventual consistency) یعنی داده بالاخره درست می‌شود، پس چیزی برای طراحی نیست.» معنایش این است که اگر تغییر دیگری نیاید نسخه‌ها هم‌گرا می‌شوند؛ در این فاصله کاربر فهرست کهنه، آیتم حذف‌شده‌ای که هنوز هست و سطرهایی با نیمی از واقعیت‌ها می‌بیند، و یک باگ projector می‌تواند سطری را تا rebuild بعدی غلط نگه دارد.

تعریف: حالت‌های کلاسیک خرابی read model:

  • فهرست کهنه (Stale list): سطر هست اما وضعیت قدیمی را نشان می‌دهد («ثبت‌شده» بعد از ارسال).
  • حذف شبح‌وار و رستاخیز (Phantom delete / resurrection): آیتمی که در سمت نوشتن حذف شده هنوز در read model یا search index پیداست؛ یا یک event «به‌روزشده»ی دیررس و قدیمی‌تر سطر حذف‌شده را دوباره می‌سازد.
  • والد گم‌شده (Missing parent): ParcelDispatched پیش از OrderPlaced می‌رسد؛ projector ساده‌لوح آن را دور می‌اندازد یا crash می‌کند.
  • lost update در projector: دو event برای یک سطر هم‌زمان در دو worker پردازش می‌شوند و هرکدام کل سطر را می‌نویسد.
  • باگ projector یا event سمی (Poison event): یک event برای همیشه شکست می‌خورد و partition یا صف پشت سرش را می‌بندد.
text
     Write side                                   Search index (projected)
1    DeleteProduct p-7 (Catalog) -> ProductDeleted
2    UpdateProduct p-7 earlier -> ProductUpdated   (delayed by a retry)
3                                                 ProductDeleted applied: p-7 removed
4                                                 ProductUpdated applied: p-7 recreated  <- resurrection
-> fix: tombstone row with version; apply an update only if version > tombstone version

سناریوی واقعی: محصولی که به دلایل حقوقی حذف شده و یک ساعت هنوز قابل جست‌وجوست؛ سفارشی که «ثبت‌شده» نشان داده می‌شود در حالی که بسته دم در است؛ تغییر نشانی مشتری که در ابزار پشتیبانی نیامده؛ شمارش فهرستی که بعد از یک تکرار با تعداد سطرها جور نیست.

خرابیطراحی‌ای که جلویش را می‌گیرد یا پنهانش می‌کند
فهرست کهنهزمان «به‌روز تا» یا برچسب «در حال پردازش»؛ read-your-writes برای عامل
حذف شبح‌وارحذف هم event است؛ یک سنگ‌قبر (Tombstone) با deleted_at و version نگه دارید و رویش فیلتر کنید
رستاخیز با event قدیمیversion guard: فقط اگر version event از version ذخیره‌شده بزرگ‌تر است اعمال کن
والد گم‌شدهupsert ستون‌های خودی؛ وضعیت مشتق؛ هشدار برای سطرهای ماندگار در «pending»
نویسنده‌های هم‌زمان یک سطرهر event فقط ستون‌های خودش را عوض کند؛ partition بر اساس شناسهٔ سفارش؛ یا قفل سطر
event سمیتلاش دوباره با backoff، بعد dead-letter (DLQ)؛ هرگز جریان را برای همیشه نبندید
باگ projectorکد را درست کنید، از روی log بازسازی کنید، جایگزین کنید

راه‌حل / نحوهٔ استفاده: سنگ‌قبر به‌اضافهٔ version guard.

sql
-- ProductDeleted: keep the row as a tombstone; searches filter deleted_at IS NULL.
UPDATE product_search SET deleted_at = $2, version = $3 WHERE product_id = $1 AND version < $3;
-- ProductUpdated: never resurrect a newer tombstone.
UPDATE product_search SET name = $2, version = $3 WHERE product_id = $1 AND version < $3;

گزارش‌گیری و تحلیل (Reporting) مهم ​

به زبان ساده: تحلیلگرها همه‌چیز را joinشده با همه‌چیز و در طول سال‌ها می‌خواهند. یک نسخهٔ جدا که برای همین ساخته شده به آن‌ها بدهید؛ هرگز ابزار BI را به دیتابیس production سرویس‌ها وصل نکنید.

بدفهمی رایج: «یک read replica از هر سرویس برای گزارش کافی است.» هنوز schema درونی هر صاحب است (پس هر تغییر نام گزارشی را می‌شکند)، joinها هنوز از دیتابیس‌ها عبور می‌کنند و query تحلیلی طولانی روی یک hot standby یا تعارض replication می‌سازد یا replay را عقب می‌اندازد.

تعریف: دیتابیس گزارش Fowler: "a completely different database to the operational database" که "designed around the reporting needs" است و با "an overnight run" یا "a messaging system so that any changes to the operational database are forwarded to the reporting database" به‌روز می‌ماند. در مقیاس بزرگ این یک انبار داده (Warehouse) یا lakehouse است که با CDC یا eventهای منتشرشده پر می‌شود (OLTP در برابر OLAP، معماری‌های Big Data).

text
1    Sales, Fulfilment, Billing commit in their own DBs
2    CDC (Debezium) or outbox events -> Kafka topics (contract tables / events only)
3    loader -> warehouse staging -> modelled tables (orders_fact, shipments_fact)
4    finance dashboard queries the warehouse (seconds), the services never notice

سناریوی واقعی: درآمد پایان ماه به تفکیک منطقه؛ صدک‌های زمان تحویل به تفکیک شرکت حمل؛ نرخ بازپرداخت برای هر محصول؛ تیم علم داده که مدل‌ها را روی تاریخچهٔ سفارش آموزش می‌دهد.

منبع گزارشتازگیبار روی سرویس‌هاپایداری schemaحکم
primary سرویس‌هازندهزیاد و غیرقابل پیش‌بینیبا هر تغییر نام می‌شکندهرگز
replica سرویس‌هاثانیهتعارض replay، تأخیربا هر تغییر نام می‌شکندپرهیز
read modelها (OrderSummary)ثانیهنداردپایدار، برای هر صفحهفقط داشبوردهای عملیاتی
warehouse از CDC/eventدقیقهنداردمدل‌شده، نسخه‌دارپیش‌فرض

راه‌حل / نحوهٔ استفاده: eventهای مناسب تحلیل یا CDC از جدول‌های قراردادی منتشر کنید؛ آن‌ها را در warehouse بار کنید؛ به صاحبان گزارش مدل خودشان را بدهید.

UI مبتنی بر وظیفه (Task-based UI) مهم ​

به زبان ساده: به‌جای فرمی که کل رکورد را ویرایش می‌کند و با PUT برمی‌گرداند، صفحه همان کارهایی را پیشنهاد می‌دهد که کاربر واقعاً انجام می‌دهد («لغو سفارش»، «تغییر نشانی تحویل»، «علامت پرداخت‌شده») و هرکدام یک فرمان کوچک با نام نیت می‌فرستد.

بدفهمی رایج: «مبتنی بر وظیفه یعنی endpointهای بیشتر برای یک کار.» یعنی کارهای متفاوت: «اصلاح غلط تایپی نشانی» و «مشتری اسباب‌کشی کرده» دو رویداد کسب‌وکاری متفاوت با قاعده‌های متفاوت‌اند (مثال Young: "Is there a difference between “Correcting an Address” and “Relocating the Customer”?").

تعریف: اسناد Young معماری DTO up/down را، که در آن "the intention of the user is being lost"، در برابر فرمان‌هایی می‌گذارند که "always in the imperative tense" هستند و فقط "data points that are required to process the given behavior" را حمل می‌کنند. سرور می‌تواند فرمان را رد کند؛ اگر نمی‌توانست، آن یک event بود. Fowler یادآوری می‌کند که دور شدن از CRUD اجازه می‌دهد "easily move to a task-based UI".

text
     CRUD screen                                     Task-based screen
1    GET /orders/o-1 -> full DTO                     GET /order-summaries/o-1 (read model)
2    user edits status, carrier, total               user clicks "Cancel order", gives a reason
3    PUT /orders/o-1 {whole DTO}                     POST /orders/o-1/cancel {reason}
4    server: which field changed, and why?           server: CancelOrder -> rule check -> OrderCancelled

سناریوی واقعی: لغو سفارش با دلیل و قاعدهٔ بازپرداخت؛ اصلاح نشانی در برابر جابه‌جایی؛ «توقف اشتراک» در برابر «تغییر طرح»؛ ابزار پشتیبانی که هر کارش با نام ممیزی می‌شود.

جنبهPUT در CRUDفرمان مبتنی بر وظیفه
نیتاز دست می‌رودنام دارد (CancelOrder)
محمولهکل رکوردفقط آنچه رفتار لازم دارد
جای قاعده‌هاپخش در validatorهاروی متد aggregate
eventها«OrderUpdated»OrderCancelled با دلیل
مناسب برایدادهٔ مرجع، فهرست‌های مدیریتیرفتار هستهٔ domain

راه‌حل / نحوهٔ استفاده: یک endpoint برای هر نیت، شناسه‌ای که کلاینت تولید می‌کند، و پاسخ 202 با توکن نسخه.

php
Route::post('/orders', [OrderCommandController::class, 'place']);          // PlaceOrder
Route::post('/orders/{order}/cancel', [OrderCommandController::class, 'cancel']); // CancelOrder (handler not shown)
Route::get('/order-summaries/{orderId}', [OrderSummaryController::class, 'show'])->name('order-summaries.show');

Event sourcing به‌عنوان گزینه‌ای برای سمت نوشتن تکمیلی ​

به زبان ساده: به‌جای ذخیرهٔ سطر فعلی سفارش، هر eventی را که برایش رخ داده ذخیره کنید و وضعیت فعلی را با بازپخش آن‌ها بسازید. آن‌وقت هر خواندنی بنا به تعریف یک projection است.

بدفهمی رایج: «CQRS و event sourcing یکی‌اند» یا «برای CQRS به event sourcing نیاز دارید». OrderSummary ما CQRS را با یک aggregate معمولی Order (ذخیرهٔ وضعیت) و یک outbox به کار می‌برد.

تعریف: "Event sourcing persists the state of a business entity such an Order or a Customer as a sequence of state-changing events." هزینه‌اش: "The event store is difficult to query since it requires typical queries to reconstruct the state of the business entities … As a result, the application must use Command Query Responsibility Segregation (CQRS) to implement queries." event store، snapshot، upcasting و replay در Event Sourcing & CQRS آموزش داده شده‌اند.

text
1    state-stored: orders row {status: dispatched, version: 3} + outbox events (this page)
2    event-sourced: OrderPlaced(v1), OrderPaid(v2), OrderDispatched(v3) are the only truth
3    read models in both cases: projections of the events
4    difference: with event sourcing the write side can be replayed too (audit, temporal queries)

سناریوی واقعی: دفتر کل و پرداخت‌هایی که حسابرس‌ها هر تغییرشان را می‌خواهند؛ domainهایی که «ساعت ۱۰:۴۲ چه می‌دانستیم؟» پرسش واقعی است؛ ویرایش مشارکتی. نه برای: مدیریت کاتالوگ، پروفایل کاربر، بیشتر CRUDها.

سمت نوشتنممیزی/تاریخچهپرس‌وجو از سمت نوشتنمنحنی یادگیریکِی
ذخیرهٔ وضعیت + outboxفقط آنچه منتشر می‌کنیدبله (SQL)کمپیش‌فرض
Event-sourcedکامل، بنا به ساختارنه؛ فقط projectionزیادdomainهای هسته با ممیزی سنگین

راه‌حل / نحوهٔ استفاده: برای هر bounded context جداگانه تصمیم بگیرید، آن هم بعد از اینکه CQRS آن‌جا مفید بودنش را ثابت کرد؛ فقط برای مسئلهٔ read model سراغش نروید.

تست projectionها تکمیلی ​

به زبان ساده: projector تابعی خالص از event به سطر است، پس با دادن دنباله‌های ضبط‌شدهٔ event (fixture) و مقایسهٔ سطرهای حاصل با سطرهای مورد انتظار تستش کنید، از جمله با تکرار، جابه‌جایی ترتیب و بازسازی.

بدفهمی رایج: «تست‌های end-to-end از راه broker projector را پوشش می‌دهند.» کندند و به‌ندرت eventها را دوبار یا نامرتب تحویل می‌دهند، و projectorها دقیقاً همان‌جا می‌شکنند.

تعریف: replay fixtureها فهرست‌های مرتب envelope هستند (اغلب از production ضبط و ناشناس‌سازی شده)؛ snapshot testها (golden file) سطر مورد انتظار read model را به‌صورت JSON نگه می‌دارند و با هر تفاوتی شکست می‌خورند؛ تست‌های property-style fixture را به‌هم می‌ریزند و تکرار می‌کنند و ادعا می‌کنند سطر نهایی یکی است؛ تست‌های rebuild log را در انباری خالی بازپخش می‌کنند و با انبار زنده مقایسه می‌کنند.

text
1    fixture: [dispatched, placed, paid]          -> row R
2    fixture + fixture (duplicates)            -> row R, log has 3 events
3    shuffle(fixture)                           -> row R
4    rebuild(log) into empty store              -> row R
5    golden file testdata/order_summary.golden.json == JSON(R)

سناریوی واقعی: فیلد تازه‌ای که به OrderPlaced v1 اضافه شده؛ بازنویسی SQL مربوط به projector؛ تغییر ترتیب eventها در Kafka بعد از repartition؛ گزارش باگ «سفارش‌های ارسال‌شده ثبت‌شده نشان داده می‌شوند».

تستچه چیزی را می‌گیردسرعت
unit test برای هر نوع eventباگ نگاشتمیلی‌ثانیه
replay fixture + snapshotهر تغییری در سطر نهاییمیلی‌ثانیه
تست تکرار/به‌هم‌ریختنباگ idempotency و ترتیبمیلی‌ثانیه
rebuild برابر زندهprojector به وضعیت پنهان وابسته استمیلی‌ثانیه (حافظه) تا ثانیه (دیتابیس)
contract test روی schema eventتولیدکننده فیلدی را عوض کردهثانیه

راه‌حل / نحوهٔ استفاده: snapshot test در Go (بعد از یک تغییر عمدی go test ./readmodel -update را اجرا کنید و diff فایل golden را در code review ببینید):

go
package readmodel

import (
	"context"
	"encoding/json"
	"flag"
	"os"
	"testing"
	"time"

	"academy/microservices-data-patterns/contracts"
)

var update = flag.Bool("update", false, "rewrite golden files")

type lagSpy struct{ n int }

func (l *lagSpy) Observe(string, time.Duration) { l.n++ }

func project(t *testing.T, events []contracts.Envelope) (*Memory, *lagSpy) {
	t.Helper()
	store, lag := NewMemory(), &lagSpy{}
	p := &Projector{Store: store, Lag: lag, Now: func() time.Time { return t0.Add(5 * time.Minute) }}
	for _, e := range events {
		if err := p.Handle(context.Background(), e); err != nil {
			t.Fatal(err)
		}
	}
	return store, lag
}

func TestOutOfOrderEventsConverge(t *testing.T) {
	store, _ := project(t, fixture())
	got, _, _ := store.Get(context.Background(), "o-1")
	if got.Status() != "completed" || got.TotalMinor != 2500 || got.Carrier != "DHL" {
		t.Fatalf("got %+v status %s", got, got.Status())
	}
}

func TestDispatchedBeforePlacedIsPending(t *testing.T) {
	store, _ := project(t, fixture()[:1])
	got, _, _ := store.Get(context.Background(), "o-1")
	if got.Status() != "pending" {
		t.Fatalf("want pending, got %s", got.Status())
	}
}

func TestDuplicateDeliveryIsANoOp(t *testing.T) {
	ev := fixture()
	store, lag := project(t, append(ev, ev...))
	if lag.n != 3 {
		t.Fatalf("want 3 applied, got %d", lag.n)
	}
	n, _ := store.ReplayAfter(context.Background(), 0, 0, func(int64, contracts.Envelope) error { return nil })
	if n != 3 {
		t.Fatalf("log should hold 3 unique events, got %d", n)
	}
}

func TestStaleSalesVersionIsIgnored(t *testing.T) {
	ev := fixture()
	older := mustEnv("evt-placed-0", "/sales", contracts.TypeOrderPlacedV1, "o-1", t0.Add(-time.Hour), 0,
		contracts.OrderPlacedV1{OrderID: "o-1", TotalMinor: 1})
	store, _ := project(t, append(ev, older))
	got, _, _ := store.Get(context.Background(), "o-1")
	if got.TotalMinor != 2500 {
		t.Fatalf("stale event overwrote the row: %+v", got)
	}
}

func TestUnknownTypeIsIgnored(t *testing.T) {
	unknown := mustEnv("evt-x", "/sales", "sales.order.gift_wrapped.v1", "o-1", t0, 2, map[string]string{})
	store, _ := project(t, []contracts.Envelope{unknown})
	if _, ok, _ := store.Get(context.Background(), "o-1"); ok {
		t.Fatal("unknown event created a row")
	}
}

func TestRebuildEqualsLive(t *testing.T) {
	live, _ := project(t, fixture())
	fresh := NewMemory()
	last, err := Rebuild(context.Background(), live, 0, 0, fresh)
	if err != nil || last != 3 {
		t.Fatalf("last=%d err=%v", last, err)
	}
	a, _, _ := live.Get(context.Background(), "o-1")
	b, _, _ := fresh.Get(context.Background(), "o-1")
	ja, _ := json.Marshal(a)
	jb, _ := json.Marshal(b)
	if string(ja) != string(jb) {
		t.Fatalf("rebuild differs\nlive:    %s\nrebuilt: %s", ja, jb)
	}
}

// TestSnapshot is a snapshot (golden-file) test: replay the fixture and compare
// the row with the committed JSON. Run `go test ./readmodel -update` after an
// intended change and review the diff in code review.
func TestSnapshot(t *testing.T) {
	store, _ := project(t, fixture())
	got, _, _ := store.Get(context.Background(), "o-1")
	b, _ := json.MarshalIndent(struct {
		OrderSummary
		Status string `json:"status"`
	}{got, got.Status()}, "", "  ")
	path := "testdata/order_summary.golden.json"
	if *update {
		if err := os.WriteFile(path, b, 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	if string(want) != string(b) {
		t.Fatalf("snapshot mismatch\nwant: %s\ngot:  %s", want, b)
	}
}

پایش projectionها (Observability) مهم ​

به زبان ساده: باید هر لحظه بتوانید جواب دهید «read model چقدر عقب است و آیا جلو می‌رود؟»، و باید بتوانید آن را با یک فرمان بازسازی کنید.

بدفهمی رایج: «طول صف تأخیر را می‌گوید.» صف می‌تواند خالی باشد چون relay انتشار را متوقف کرده؛ عددی که کاربر حس می‌کند سنِ تازه‌ترین واقعیتی است که read model اعمال کرده، برای هر منبع.

تعریف: تأخیر projection = اکنون منهای زمان event آخرین event اعمال‌شده (برای هر منبع)، یا تأخیر زمان event که هنگام اعمال اندازه گرفته می‌شود (histogram). این‌ها را هم ببینید: lag مصرف‌کننده (offsetهای Kafka، عمق صف RabbitMQ)، تعداد dead-letter، سطرهای ماندگار در «pending»، مدت rebuild، و WAL نگه‌داشته‌شده توسط replication slot برای CDC یا logical replication.

text
1    metric projection_lag_seconds{projection="order_summary",source="/billing"}  p99 0.4 s
2    alert: lag > 30 s for 5 min, or no applied events for 10 min while the outbox has rows
3    dashboard: lag per source, applied/s, duplicates/s, DLQ size, pending rows
4    runbook: pause projector -> fix -> order-summary:rebuild -> swap -> resume

سناریوی واقعی: relay مربوط به Billing بعد از یک deploy متوقف شد و «پرداخت‌شده» هرگز نیامد؛ consumer group در Kafka در حلقهٔ rebalance گیر کرد؛ یک replication slot دیسک primary در Billing را پر کرد؛ rebuildی که ۳ ساعت طول کشید چون جدول log روی position index نداشت.

سیگنالکجامعنا
projection_lag_seconds برای هر منبعprojector (histogram در Prometheus)کهنگی‌ای که کاربر می‌بیند
lag مصرف‌کنندهoffsetهای Kafka / عمق صف RabbitMQکارهای عقب‌افتادهٔ تحویل‌نشده
نرخ received_events در برابر نرخ outboxهر دو سمتrelay یا consumer متوقف شده
سطرهای placed_at IS NULL قدیمی‌تر از ۱۰ دقیقهانبار خواندنوالد گم‌شده / event گم‌شده
اندازهٔ DLQbrokereventهای سمی
WAL نگه‌داشته در pg_replication_slotsPostgreSQL صاحبCDC یا subscriber گیرکرده

راه‌حل / نحوهٔ استفاده: query تأخیر از schema سمت خواندن (در سازوکار هم هست)، و LagRecorder مربوط به projector در Go یا سطر log به نام projection.applied در Laravel.

sql
SELECT source, now() - max(occurred_at) AS lag_by_event_time, now() - max(received_at) AS since_last_delivery
FROM received_events GROUP BY source;

سازوکار (Mechanics) ​

schema سمت خواندن ​

دو جدول. received_events هم کلید dedup است (UNIQUE event_id) و هم log بازپخش (position از نوع identity). order_summary ستون‌هایش را بر اساس context صاحب گروه‌بندی می‌کند تا هر نوع event فقط گروه خودش را بنویسد. دو query آخر metric تأخیر و هشدار «pending ماندگار» هستند.

sql
-- Read side of the "My orders" screen, owned by the read-model service
-- (or by the Sales module's read side in a modular monolith).

-- 1. Every integration event this read side has received: dedup key + replay log.
CREATE TABLE received_events (
  position       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_id       text        NOT NULL UNIQUE,      -- idempotency: one row per event id
  source         text        NOT NULL,             -- /sales, /fulfilment, /billing
  type           text        NOT NULL,             -- sales.order.placed.v1 ...
  subject        text        NOT NULL,             -- order id
  source_version bigint      NOT NULL,
  occurred_at    timestamptz NOT NULL,
  received_at    timestamptz NOT NULL DEFAULT now(),
  payload        jsonb       NOT NULL
);

-- 2. The read model: one denormalised row per order, columns grouped by owner.
CREATE TABLE order_summary (
  order_id      text PRIMARY KEY,
  -- Sales columns (from sales.order.placed.v1), guarded by sales_version
  customer_id   text,
  currency      char(3),
  total_minor   bigint NOT NULL DEFAULT 0,
  line_count    int    NOT NULL DEFAULT 0,
  sales_version bigint NOT NULL DEFAULT 0,
  placed_at     timestamptz,
  -- Fulfilment columns (from fulfilment.parcel.dispatched.v1)
  dispatched_at    timestamptz,
  carrier       text,
  tracking_ref  text,
  -- Billing columns (from billing.invoice.paid.v1)
  paid_at       timestamptz,
  paid_minor    bigint NOT NULL DEFAULT 0,
  updated_at    timestamptz NOT NULL DEFAULT now()
);

-- Indexes follow the screens, not the domain: "my orders, newest first".
CREATE INDEX order_summary_customer_placed ON order_summary (customer_id, placed_at DESC);

-- 3. Projection lag per source: how old is the newest fact we have applied?
SELECT source,
       now() - max(occurred_at) AS lag_by_event_time,
       now() - max(received_at) AS since_last_delivery
FROM received_events
GROUP BY source;

-- 4. Orders stuck in "pending" (a Fulfilment/Billing fact arrived, OrderPlaced did not).
SELECT order_id, updated_at
FROM order_summary
WHERE placed_at IS NULL AND updated_at < now() - interval '10 minutes';

الگوریتم projection، قدم‌به‌قدم ​

text
     Projector worker (one delivery)
1    receive envelope {id, source, type, subject, time, sourceversion, data}
2    Decode(type): unknown type -> ack and skip (forward compatible); bad payload -> error -> retry -> DLQ
3    BEGIN
4    INSERT INTO received_events (...) ON CONFLICT (event_id) DO NOTHING
5    rows affected = 0 -> COMMIT; ack; stop (duplicate)
6    INSERT INTO order_summary (own columns) ON CONFLICT (order_id) DO UPDATE SET own columns
        [Sales only: WHERE s.sales_version < EXCLUDED.sales_version]
7    COMMIT
8    ack the message (after commit: a crash before ack only causes a redelivery, which step 5 absorbs)
9    observe lag = now - envelope.time

دو ویژگی این کار را بدون تراکنش توزیع‌شده امن می‌کند: insert مربوط به dedup و به‌روزرسانی سطر در یک تراکنش محلی‌اند، و ack به broker بعد از commit می‌آید (حداقل یک‌بار). هم‌روندی: دو worker که دو event از یک سفارش را پردازش می‌کنند به ستون‌های متفاوت دست می‌زنند و قفل سطری که ON CONFLICT DO UPDATE می‌گیرد آن‌ها را پشت سر هم می‌اندازد. partition کردن بر اساس subject (کلید Kafka، consistent-hash exchange در RabbitMQ) همین رقابت را هم حذف می‌کند (Ordering & Partitioning).

بازسازی و جایگزینی (Rebuild and swap) ​

text
     Rebuild job                                          Live projector (several workers)
1    CREATE TABLE order_summary_rebuild (LIKE order_summary INCLUDING ALL)
2    fence F1: BEGIN; LOCK received_events EXCLUSIVE;      in-flight inserts finish first,
       SELECT max(position); COMMIT                          new ones wait a moment
3    replay positions 1..F1 into _rebuild                  keeps applying F1+1, F1+2 ... to order_summary
4    catch-up: fence F2, replay F1+1..F2 (repeat a few times)
5    BEGIN; LOCK TABLE received_events IN EXCLUSIVE MODE   new ApplyOnce calls wait (plain SELECTs do not)
6    replay F2+1..end into _rebuild                        (complete: no inserter is open)
7    RENAME order_summary -> _old, _rebuild -> order_summary; DROP _old
                                                           readers of order_summary wait (ACCESS EXCLUSIVE)
8    COMMIT                                                waiting calls continue on the new table

چرا حصار (fence). position مقدار identity است که هنگام درج سطر داده می‌شود، نه هنگام commit. با چند worker در projector، موقعیت ۱۱ می‌تواند commit شود در حالی که ۱۰ هنوز باز است؛ دوری که «هرچه بعد از ۹» را می‌خواند ۱۱ را می‌بیند، ۱۱ را انجام‌شده ثبت می‌کند و ۱۰ هرگز بازپخش نمی‌شود، حتی در دنبالهٔ نهایی، و بعد جایگزینی تنها جدولی را که آن را داشت دور می‌اندازد. گرفتن LOCK TABLE received_events IN EXCLUSIVE MODE منتظر همهٔ درج‌کننده‌های باز می‌ماند، پس max(position) که زیر این قفل خوانده شود موقعیتی است که هرچه پایین‌تر از آن است commit شده. جدول قفل‌های PostgreSQL: INSERT قفل ROW EXCLUSIVE می‌گیرد که با EXCLUSIVE تعارض دارد؛ و EXCLUSIVE "allows only concurrent ACCESS SHARE locks"، یعنی خواندن سادهٔ log ادامه پیدا می‌کند. جایگزینی برای خواننده‌ها نامرئی نیست: ALTER TABLE … RENAME قفل ACCESS EXCLUSIVE می‌گیرد ("An ACCESS EXCLUSIVE lock is acquired unless explicitly noted") و "Only an ACCESS EXCLUSIVE lock blocks a SELECT"، پس queryهای روی order_summary برای چند میلی‌ثانیهٔ قدم ۷ و ۸ صبر می‌کنند. هر دو تراکنش اول log و بعد جدول خلاصه را قفل می‌کنند، پس جایگزینی با ApplyOnce به deadlock نمی‌خورد. اگر نمی‌خواهید به این‌ها فکر کنید، projector را برای مدت بازسازی متوقف کنید (queue:pause، توقف consumer)؛ broker پیام‌ها را نگه می‌دارد. نسخهٔ تازهٔ read model (ستون‌ها و شکل تازه) با همین روال و یک projector تازه ساخته می‌شود، یا با order_summary_v2 کنار نسخهٔ قبلی که خواننده‌ها با تنظیمات به آن سوییچ می‌کنند.

تنظیمات هر محصول ​

محصولتنظیماین‌جا چه می‌کند
Laravel 13'sticky' => true روی اتصال خواندن/نوشتنخواندن‌های بعد از نوشتن در همان درخواست به host نوشتن می‌روند
Laravel 13DB::withoutAffectingStickiness(fn)نوشتن‌هایی (ممیزی، پیشرفت) که نباید خواندن را چسبنده کنند
Laravel 13ShouldQueueAfterCommit روی listenerlistener فقط بعد از commit تراکنش باز در صف می‌رود
Laravel 13after_commit در config/queue.phpهمین، برای همهٔ jobهای آن اتصال
Laravel 13ShouldDispatchAfterCommit روی eventevent فقط بعد از commit dispatch می‌شود؛ با rollback دور ریخته می‌شود
Laravel 13$tries و backoff() روی listener صف‌شدهسیاست تلاش دوباره پیش از failed_jobs
Laravel 13ShouldBeUniqueفقط یک نمونه از job/listener هم‌زمان در صف (dedup event نیست)
Laravel Scoutگزینهٔ queue و trait به نام Searchableهم‌گام‌سازی index از راه model observer، صف‌شده
PostgreSQLwal_level = logicalبرای logical replication و Debezium لازم است
PostgreSQLmax_replication_slots، max_wal_sendersظرفیت برای subscriberها و connectorهای CDC
PostgreSQLCREATE PUBLICATION … (cols) WHERE (…)، WITH (publish = 'insert')فهرست ستون، row filter، عملیات
PostgreSQLREPLICA IDENTITYبرای replicate کردن UPDATE/DELETE لازم است؛ row filter و فهرست ستون را محدود می‌کند
PostgreSQLREFRESH MATERIALIZED VIEW CONCURRENTLYتازه‌سازی بدون بستن خواننده‌ها؛ index یکتا می‌خواهد
PostgreSQLALTER TABLE … ENABLE ALWAYS TRIGGERاجرای trigger مربوط به projection در apply worker مربوط به logical replication
Debeziumplugin.name=pgoutput، publication.autocreate.mode=filteredاستفاده از plugin توکار، ساختن publication فقط برای جدول‌های شامل‌شده
Debeziumtable.include.list، column.include.listفقط جدول و ستون‌های قراردادی را بگیر
Debeziumsnapshot.mode=initialsnapshot از سطرهای موجود (op: r) پیش از stream
Debeziumheartbeat.interval.msslot را وقتی جدول‌های گرفته‌شده ساکت‌اند جلو می‌برد
Kafkaکلید = شناسهٔ سفارش؛ retention یا compaction تاپیکترتیب برای هر سفارش؛ replay تا کجا عقب می‌رود

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

خطاکجامعنا و راه‌حل
duplicate key value violates unique constraint "received_events_event_id_key" (SQLSTATE 23505)PostgreSQLیک INSERT ساده به تحویل دوباره خورده؛ از ON CONFLICT DO NOTHING استفاده کنید (یا خطا را بگیرید)
Illuminate\Database\UniqueConstraintViolationExceptionLaravelهمان، از Eloquent یا query builder؛ insertOrIgnore از آن پرهیز می‌کند
MySQL 1062 Duplicate entryMySQLهمان روی MySQL؛ INSERT IGNORE / insertOrIgnore
permission denied for schema sales (42501)PostgreSQLسرویسی به schema سرویس دیگر دست زده: قاعدهٔ مالکیت کار کرد
cannot refresh materialized view "…" concurrentlyPostgreSQLindex یکتای مناسب روی materialized view نیست
cannot update table "…" because it does not have a replica identity and publishes updatesPostgreSQL ناشرREPLICA IDENTITY بگذارید یا فقط insert منتشر کنید
replication slot "…" is active for PID …PostgreSQLدو connector روی یک slot؛ برای هر slot یک connector در CDC
deadlock detected (40P01)PostgreSQLprojector چند سطر را با ترتیب‌های مختلف به‌روز می‌کند؛ بر اساس کلید partition یا مرتب کنید (Deadlocks)
ErrNotYetProjected / HTTP 202 + Retry-AfterAPI پرس‌وجوی ماread model در بودجه به version کلاینت نرسیده

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

محصولقابلیتی که به‌عنوان سمت خواندن استفاده می‌شودرفتاری که باید بدانید
PostgreSQLجدول، upsert، materialized view، logical replicationON CONFLICT قفل سطر می‌گیرد؛ DDL منتقل نمی‌شود؛ refresh در matview محاسبهٔ کامل است
MySQL / InnoDBread replica (binlog)، INSERT … ON DUPLICATE KEY UPDATE، INSERT IGNOREmaterialized view ندارد؛ replicaها عقب می‌افتند؛ dedup با کلید یکتا به‌اضافهٔ INSERT IGNORE
MongoDBیک سند برای هر صفحه؛ change stream به‌عنوان منبع CDCبرای سندهای هر صفحه طبیعی است؛ change stream به replica set نیاز دارد
Elasticsearch / OpenSearchread model جست‌وجوتقریباً بلادرنگ: سند بعد از refresh بعدی قابل جست‌وجوست؛ برای جلوگیری از رستاخیز از external versioning استفاده کنید
Redisread model کلید-مقدار، شمارنده‌هاسریع؛ log نیست، پس از log خودتان بازسازی کنید نه از Redis
Kafkaانتقال؛ تاپیک compacted به‌عنوان منبع «آخرین وضعیت هر کلید»retention تعیین می‌کند replay تا کجا عقب برود؛ compaction آخرین مقدار هر کلید را نگه می‌دارد
DebeziumCDC از PostgreSQL/MySQL/MongoDB به Kafkaهنگام خرابی حداقل یک‌بار؛ اول snapshot بعد stream؛ یک slot برای هر connector
Laravel Scoutهم‌گام‌سازی search index از مدل‌های Eloquentمبتنی بر observer، به شکل همان مدل؛ درون یک صاحب خوب است، نه برای read model چندصاحبه

Go ​

ماژول Go (academy/microservices-data-patterns، با pgx v5) سمت نوشتن، سمت خواندن و یک انبار درون‌حافظه‌ای با همان قرارداد انبار PostgreSQL را دارد، پس go test ./... تکرار، جابه‌جایی ترتیب، version کهنه، rebuild و read-your-writes را بدون دیتابیس امتحان می‌کند.

قراردادها: سه صاحب، یک envelope ​

go
// Package contracts holds the integration events the OrderSummary read model
// consumes. Each type is owned by the context that publishes it: Sales owns
// sales.*, Fulfilment owns fulfilment.*, Billing owns billing.*. The read side
// only depends on these published shapes, never on another context's tables.
package contracts

import (
	"encoding/json"
	"time"
)

// Envelope uses CloudEvents attribute names in its JSON form.
// SourceVersion is the publishing aggregate's version after the change; a
// consumer uses it to ignore stale or reordered events from the same source.
type Envelope struct {
	ID            string          `json:"id"`
	Source        string          `json:"source"`
	Type          string          `json:"type"`
	Subject       string          `json:"subject"` // the order id for all three types
	Time          time.Time       `json:"time"`
	SourceVersion int64           `json:"sourceversion"`
	Data          json.RawMessage `json:"data"`
}

// Contract names: <context>.<entity>.<fact>.v<major>.
const (
	TypeOrderPlacedV1      = "sales.order.placed.v1"
	TypeParcelDispatchedV1 = "fulfilment.parcel.dispatched.v1"
	TypeInvoicePaidV1      = "billing.invoice.paid.v1"
)

// OrderPlacedV1 is published by Sales when an Order aggregate is placed.
type OrderPlacedV1 struct {
	OrderID    string `json:"orderId"`
	CustomerID string `json:"customerId"`
	TotalMinor int64  `json:"totalMinor"`
	Currency   string `json:"currency"`
	LineCount  int    `json:"lineCount"`
}

// ParcelDispatchedV1 is published by Fulfilment when the parcel leaves the warehouse.
type ParcelDispatchedV1 struct {
	OrderID     string `json:"orderId"`
	ShipmentID  string `json:"shipmentId"`
	Carrier     string `json:"carrier"`
	TrackingRef string `json:"trackingRef"`
}

// InvoicePaidV1 is published by Billing when the invoice for an order is paid.
type InvoicePaidV1 struct {
	OrderID   string `json:"orderId"`
	InvoiceID string `json:"invoiceId"`
	PaidMinor int64  `json:"paidMinor"`
}

// New builds an envelope; tests and the demo use it.
func New(id, source, typ, subject string, at time.Time, version int64, payload any) (Envelope, error) {
	raw, err := json.Marshal(payload)
	if err != nil {
		return Envelope{}, err
	}
	return Envelope{ID: id, Source: source, Type: typ, Subject: subject, Time: at, SourceVersion: version, Data: raw}, nil
}

CQS در سطح متد ​

go
// Package cqs shows Command-Query Separation at the method level: a command
// changes state and returns only an error; a query returns data and changes
// nothing observable.
package cqs

import "errors"

// ErrNotPaid is returned when a rule rejects a command.
var ErrNotPaid = errors.New("order is not paid")

// Status is a small value type.
type Status string

const (
	Placed     Status = "placed"
	Paid       Status = "paid"
	Dispatched Status = "dispatched"
)

// Order is a tiny aggregate used only to show the method shapes.
type Order struct {
	id      string
	status  Status
	version int64
}

// NewOrder places an order (a constructor is allowed to return the object).
func NewOrder(id string) *Order { return &Order{id: id, status: Placed, version: 1} }

// MarkPaid is a COMMAND: it mutates and returns only an error.
func (o *Order) MarkPaid() error {
	if o.status != Placed {
		return errors.New("only a placed order can be paid")
	}
	o.status = Paid
	o.version++
	return nil
}

// Dispatch is a COMMAND guarded by a rule.
func (o *Order) Dispatch() error {
	if o.status != Paid {
		return ErrNotPaid
	}
	o.status = Dispatched
	o.version++
	return nil
}

// Status is a QUERY: no side effects, safe to call any number of times in any order.
func (o *Order) Status() Status { return o.status }

// Version is a QUERY; the application layer reads it after a command to hand
// the caller a consistency token (see the query package).
func (o *Order) Version() int64 { return o.version }

// CanDispatch is a QUERY that answers a question without changing the answer.
func (o *Order) CanDispatch() bool { return o.status == Paid }

سمت نوشتن: aggregate به نام Order و handler یک فرمان مبتنی بر وظیفه ​

handler یک Ack با version تازه برمی‌گرداند، نه دادهٔ خواندنی: همین توکن سازگاری است.

go
// Package sales is the WRITE side: the Order aggregate, a task-based command
// and its handler. Nothing here is shaped for screens.
package sales

import (
	"errors"
	"time"
)

// Line is one order line (value object).
type Line struct {
	SKU        string
	Quantity   int
	PriceMinor int64
}

// Order is the aggregate root. Its fields are private: screens read the
// OrderSummary read model, not this object.
type Order struct {
	id         string
	customerID string
	lines      []Line
	currency   string
	placedAt   time.Time
	version    int64
	pending    []Placed
}

// Placed is the domain event recorded by Place.
type Placed struct {
	OrderID    string
	CustomerID string
	TotalMinor int64
	Currency   string
	LineCount  int
	Version    int64
	At         time.Time
}

// ErrEmptyOrder is a rule violation.
var ErrEmptyOrder = errors.New("an order needs at least one line")

// Place is the factory for a new order. The client supplies the id (a UUID),
// so the command needs no return value to tell the caller what was created.
func Place(id, customerID, currency string, lines []Line, now time.Time) (*Order, error) {
	if len(lines) == 0 {
		return nil, ErrEmptyOrder
	}
	o := &Order{id: id, customerID: customerID, lines: lines, currency: currency, placedAt: now, version: 1}
	o.pending = append(o.pending, Placed{
		OrderID: id, CustomerID: customerID, TotalMinor: o.total(), Currency: currency,
		LineCount: len(lines), Version: o.version, At: now,
	})
	return o, nil
}

func (o *Order) total() int64 {
	var t int64
	for _, l := range o.lines {
		t += l.PriceMinor * int64(l.Quantity)
	}
	return t
}

// ID and Version are queries.
func (o *Order) ID() string { return o.id }

// Version is the optimistic-concurrency version, also used as a consistency token.
func (o *Order) Version() int64 { return o.version }

// PullEvents hands recorded events to the repository and clears them.
func (o *Order) PullEvents() []Placed {
	ev := o.pending
	o.pending = nil
	return ev
}
go
package sales

import (
	"context"
	"time"
)

// PlaceOrder is a COMMAND: an intent in the imperative, carrying only what the
// behaviour needs. It is not an OrderDTO.
type PlaceOrder struct {
	OrderID    string // client-generated UUID
	CustomerID string
	Currency   string
	Lines      []Line
}

// Repository saves the aggregate and its events (outbox) in ONE local
// transaction. The PostgreSQL version lives in the aggregates chapter.
type Repository interface {
	Add(ctx context.Context, o *Order, events []Placed) error
}

// Ack is what the handler returns: no read data, only a consistency token the
// client may pass to the read side ("show me order X at version >= 1").
type Ack struct {
	OrderID string
	Version int64
}

// PlaceOrderHandler is the application service for the command.
type PlaceOrderHandler struct {
	Repo Repository
	Now  func() time.Time
}

// Handle runs the command. It returns an Ack, not an OrderSummary: reading
// the result is the query side's job.
func (h PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrder) (Ack, error) {
	o, err := Place(cmd.OrderID, cmd.CustomerID, cmd.Currency, cmd.Lines, h.Now())
	if err != nil {
		return Ack{}, err
	}
	if err := h.Repo.Add(ctx, o, o.PullEvents()); err != nil {
		return Ack{}, err
	}
	return Ack{OrderID: o.ID(), Version: o.Version()}, nil
}

سمت خواندن: مدل OrderSummary، patchها و portها ​

go
// Package readmodel is the QUERY side: the OrderSummary read model, the
// patches events turn into, and the projector that applies them.
package readmodel

import (
	"context"
	"time"

	"academy/microservices-data-patterns/contracts"
)

// OrderSummary is one row per order, shaped for the "My orders" screen and the
// support tool. It joins facts owned by three contexts; it owns none of them.
type OrderSummary struct {
	OrderID      string     `json:"orderId"`
	CustomerID   string     `json:"customerId,omitempty"`
	TotalMinor   int64      `json:"totalMinor"`
	Currency     string     `json:"currency,omitempty"`
	LineCount    int        `json:"lineCount"`
	SalesVersion int64      `json:"salesVersion"` // 0 until OrderPlaced arrives
	PlacedAt     *time.Time `json:"placedAt,omitempty"`
	DispatchedAt *time.Time `json:"dispatchedAt,omitempty"`
	Carrier      string     `json:"carrier,omitempty"`
	TrackingRef  string     `json:"trackingRef,omitempty"`
	PaidAt       *time.Time `json:"paidAt,omitempty"`
	PaidMinor    int64      `json:"paidMinor"`
}

// Status is DERIVED from which facts have arrived, so the order in which the
// three contexts' events arrive does not matter.
func (s OrderSummary) Status() string {
	switch {
	case s.PlacedAt == nil:
		return "pending" // a Fulfilment or Billing fact arrived before OrderPlaced
	case s.DispatchedAt != nil && s.PaidAt != nil:
		return "completed"
	case s.DispatchedAt != nil:
		return "dispatched"
	case s.PaidAt != nil:
		return "paid"
	default:
		return "placed"
	}
}

// Patch is the part of the row one event type owns. Each context's event
// touches only its own columns, so concurrent or reordered events never undo
// each other.
type Patch interface{ orderID() string }

// PlacedPatch owns the Sales columns; it is applied only if SalesVersion grows.
type PlacedPatch struct {
	OrderID, CustomerID, Currency string
	TotalMinor                    int64
	LineCount                     int
	SalesVersion                  int64
	PlacedAt                      time.Time
}

// DispatchedPatch owns the Fulfilment columns.
type DispatchedPatch struct {
	OrderID, Carrier, TrackingRef string
	DispatchedAt                  time.Time
}

// PaidPatch owns the Billing columns.
type PaidPatch struct {
	OrderID   string
	PaidMinor int64
	PaidAt    time.Time
}

func (p PlacedPatch) orderID() string     { return p.OrderID }
func (p DispatchedPatch) orderID() string { return p.OrderID }
func (p PaidPatch) orderID() string       { return p.OrderID }

// Store is the read store plus its received-events log. ApplyOnce must append
// the envelope to the log (unique on event id) and apply the patch in ONE
// transaction; it reports false for a duplicate.
type Store interface {
	ApplyOnce(ctx context.Context, env contracts.Envelope, p Patch) (bool, error)
	Get(ctx context.Context, orderID string) (OrderSummary, bool, error)
}

// Log is the append-only copy of every integration event this read side has
// received. It is the replay source for rebuilds: Fulfilment's and Billing's
// own databases are not ours to read. ReplayAfter visits positions in
// (after, upTo]; upTo = 0 means no upper bound.
type Log interface {
	ReplayAfter(ctx context.Context, after, upTo int64, fn func(pos int64, env contracts.Envelope) error) (last int64, err error)
}

// Target receives patches during a rebuild (no dedup: the log is already unique).
type Target interface {
	Apply(ctx context.Context, p Patch) error
}

projector: decode، یک‌بار اعمال، اندازه‌گیری تأخیر، بازسازی ​

go
package readmodel

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"academy/microservices-data-patterns/contracts"
)

// LagRecorder receives the projection lag: now minus the event's time.
// In production this is a Prometheus histogram labelled by source.
type LagRecorder interface {
	Observe(source string, lag time.Duration)
}

// Projector turns integration events into read-model patches.
type Projector struct {
	Store Store
	Lag   LagRecorder
	Now   func() time.Time
}

// Decode maps an envelope to a patch. Unknown types return (nil, nil): a new
// event type published tomorrow must not crash today's projector.
func Decode(env contracts.Envelope) (Patch, error) {
	switch env.Type {
	case contracts.TypeOrderPlacedV1:
		var d contracts.OrderPlacedV1
		if err := json.Unmarshal(env.Data, &d); err != nil {
			return nil, fmt.Errorf("decode %s %s: %w", env.Type, env.ID, err)
		}
		return PlacedPatch{OrderID: d.OrderID, CustomerID: d.CustomerID, Currency: d.Currency,
			TotalMinor: d.TotalMinor, LineCount: d.LineCount, SalesVersion: env.SourceVersion, PlacedAt: env.Time}, nil
	case contracts.TypeParcelDispatchedV1:
		var d contracts.ParcelDispatchedV1
		if err := json.Unmarshal(env.Data, &d); err != nil {
			return nil, fmt.Errorf("decode %s %s: %w", env.Type, env.ID, err)
		}
		return DispatchedPatch{OrderID: d.OrderID, Carrier: d.Carrier, TrackingRef: d.TrackingRef, DispatchedAt: env.Time}, nil
	case contracts.TypeInvoicePaidV1:
		var d contracts.InvoicePaidV1
		if err := json.Unmarshal(env.Data, &d); err != nil {
			return nil, fmt.Errorf("decode %s %s: %w", env.Type, env.ID, err)
		}
		return PaidPatch{OrderID: d.OrderID, PaidMinor: d.PaidMinor, PaidAt: env.Time}, nil
	}
	return nil, nil
}

// Handle is the projection handler the consumer calls for every delivery.
// Delivery is at-least-once, so the same envelope may arrive twice; ApplyOnce
// makes the second delivery a no-op.
func (p *Projector) Handle(ctx context.Context, env contracts.Envelope) error {
	patch, err := Decode(env)
	if err != nil || patch == nil {
		return err // a decode error goes to the DLQ via the consumer's retry policy
	}
	applied, err := p.Store.ApplyOnce(ctx, env, patch)
	if err != nil {
		return err
	}
	if applied && p.Lag != nil {
		p.Lag.Observe(env.Source, p.Now().Sub(env.Time))
	}
	return nil
}

// Rebuild replays the received-events log in (after, upTo] into a fresh target
// (a new table or a new index). Run it for a new read-model version or after a
// projector bug; then switch readers to the new target. upTo must be a fence:
// a position below which every log insert has committed (see pgstore).
func Rebuild(ctx context.Context, log Log, after, upTo int64, target Target) (int64, error) {
	return log.ReplayAfter(ctx, after, upTo, func(_ int64, env contracts.Envelope) error {
		patch, err := Decode(env)
		if err != nil || patch == nil {
			return err
		}
		return target.Apply(ctx, patch)
	})
}

انبار PostgreSQL با pgx: dedup و upsert در یک تراکنش ​

go
// Package pgstore is the PostgreSQL read store for OrderSummary, using pgx.
// Schema: docs/snippets/ddd/microservices-data-patterns/sql/read_model.sql.
package pgstore

import (
	"context"
	"fmt"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"

	"academy/microservices-data-patterns/contracts"
	"academy/microservices-data-patterns/readmodel"
)

// Store implements readmodel.Store and readmodel.Log.
type Store struct {
	DB    *pgxpool.Pool
	Table string // "order_summary"; a rebuild writes "order_summary_rebuild"
}

// ApplyOnce: append to received_events (dedup by event id) and upsert the
// read row in the same transaction. A crash between the two is impossible;
// a redelivery finds the id and does nothing.
func (s Store) ApplyOnce(ctx context.Context, env contracts.Envelope, p readmodel.Patch) (bool, error) {
	applied := false
	err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
		tag, err := tx.Exec(ctx, `
			INSERT INTO received_events (event_id, source, type, subject, source_version, occurred_at, payload)
			VALUES ($1, $2, $3, $4, $5, $6, $7)
			ON CONFLICT (event_id) DO NOTHING`,
			env.ID, env.Source, env.Type, env.Subject, env.SourceVersion, env.Time, env.Data)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			return nil // duplicate delivery
		}
		applied = true
		return apply(ctx, tx, s.table(), p)
	})
	return applied, err
}

// Apply is the rebuild path (no dedup).
func (s Store) Apply(ctx context.Context, p readmodel.Patch) error {
	return apply(ctx, s.DB, s.table(), p)
}

func (s Store) table() string {
	if s.Table == "" {
		return pgx.Identifier{"order_summary"}.Sanitize()
	}
	return pgx.Identifier{s.Table}.Sanitize()
}

// execer is satisfied by both pgx.Tx and *pgxpool.Pool.
type execer interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}

// apply upserts ONLY the columns the event's context owns. The row may not
// exist yet (ParcelDispatched can arrive before OrderPlaced), so every patch is an
// INSERT ... ON CONFLICT DO UPDATE, never an UPDATE that silently hits 0 rows.
func apply(ctx context.Context, db execer, table string, p readmodel.Patch) error {
	var err error
	switch v := p.(type) {
	case readmodel.PlacedPatch:
		_, err = db.Exec(ctx, fmt.Sprintf(`
			INSERT INTO %s AS s (order_id, customer_id, currency, total_minor, line_count, sales_version, placed_at, updated_at)
			VALUES ($1, $2, $3, $4, $5, $6, $7, now())
			ON CONFLICT (order_id) DO UPDATE SET
			  customer_id = EXCLUDED.customer_id, currency = EXCLUDED.currency,
			  total_minor = EXCLUDED.total_minor, line_count = EXCLUDED.line_count,
			  sales_version = EXCLUDED.sales_version, placed_at = EXCLUDED.placed_at, updated_at = now()
			WHERE s.sales_version < EXCLUDED.sales_version`, table),
			v.OrderID, v.CustomerID, v.Currency, v.TotalMinor, v.LineCount, v.SalesVersion, v.PlacedAt)
	case readmodel.DispatchedPatch:
		_, err = db.Exec(ctx, fmt.Sprintf(`
			INSERT INTO %s (order_id, dispatched_at, carrier, tracking_ref, updated_at)
			VALUES ($1, $2, $3, $4, now())
			ON CONFLICT (order_id) DO UPDATE SET
			  dispatched_at = EXCLUDED.dispatched_at, carrier = EXCLUDED.carrier,
			  tracking_ref = EXCLUDED.tracking_ref, updated_at = now()`, table),
			v.OrderID, v.DispatchedAt, v.Carrier, v.TrackingRef)
	case readmodel.PaidPatch:
		_, err = db.Exec(ctx, fmt.Sprintf(`
			INSERT INTO %s (order_id, paid_at, paid_minor, updated_at)
			VALUES ($1, $2, $3, now())
			ON CONFLICT (order_id) DO UPDATE SET
			  paid_at = EXCLUDED.paid_at, paid_minor = EXCLUDED.paid_minor, updated_at = now()`, table),
			v.OrderID, v.PaidAt, v.PaidMinor)
	default:
		err = fmt.Errorf("unknown patch %T", p)
	}
	return err
}
go
package pgstore

import (
	"context"
	"errors"
	"fmt"

	"github.com/jackc/pgx/v5"

	"academy/microservices-data-patterns/contracts"
	"academy/microservices-data-patterns/readmodel"
)

// Get is the thin read layer: one indexed lookup, no domain objects.
func (s Store) Get(ctx context.Context, orderID string) (readmodel.OrderSummary, bool, error) {
	var r readmodel.OrderSummary
	err := s.DB.QueryRow(ctx, fmt.Sprintf(`
		SELECT order_id, coalesce(customer_id, ''), total_minor, coalesce(currency, ''), line_count,
		       sales_version, placed_at, dispatched_at, coalesce(carrier, ''), coalesce(tracking_ref, ''),
		       paid_at, paid_minor
		FROM %s WHERE order_id = $1`, s.table()), orderID).Scan(
		&r.OrderID, &r.CustomerID, &r.TotalMinor, &r.Currency, &r.LineCount,
		&r.SalesVersion, &r.PlacedAt, &r.DispatchedAt, &r.Carrier, &r.TrackingRef,
		&r.PaidAt, &r.PaidMinor)
	if errors.Is(err, pgx.ErrNoRows) {
		return r, false, nil
	}
	return r, err == nil, err
}

// ReplayAfter streams received_events in position order (a bigint identity
// column). Positions are assigned at INSERT, not at COMMIT, so a scan may see
// 11 before 10 has committed: callers pass a fence as upTo (see rebuild.go).
func (s Store) ReplayAfter(ctx context.Context, after, upTo int64, fn func(int64, contracts.Envelope) error) (int64, error) {
	rows, err := s.DB.Query(ctx, `
		SELECT position, event_id, source, type, subject, source_version, occurred_at, payload
		FROM received_events
		WHERE position > $1 AND ($2 = 0 OR position <= $2)
		ORDER BY position`, after, upTo)
	if err != nil {
		return after, err
	}
	defer rows.Close()
	last := after
	for rows.Next() {
		var pos int64
		var e contracts.Envelope
		if err := rows.Scan(&pos, &e.ID, &e.Source, &e.Type, &e.Subject, &e.SourceVersion, &e.Time, &e.Data); err != nil {
			return last, err
		}
		if err := fn(pos, e); err != nil {
			return last, err
		}
		last = pos
	}
	return last, rows.Err()
}

بازسازی و جایگزینی زیر یک قفل کوتاه ​

go
package pgstore

import (
	"context"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"

	"academy/microservices-data-patterns/contracts"
	"academy/microservices-data-patterns/readmodel"
)

// fence returns a position below which every received_events insert has
// committed. Identity values are assigned at INSERT time, so with several
// projector workers position 11 can commit before 10; a plain "position > last"
// scan would skip 10 forever. LOCK ... EXCLUSIVE waits for every open inserter
// (ROW EXCLUSIVE) to finish, so max(position) read under it is a safe fence.
func fence(ctx context.Context, db *pgxpool.Pool) (int64, error) {
	var f int64
	err := pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx, `LOCK TABLE received_events IN EXCLUSIVE MODE`); err != nil {
			return err
		}
		return tx.QueryRow(ctx, `SELECT coalesce(max(position), 0) FROM received_events`).Scan(&f)
	})
	return f, err
}

// RebuildAndSwap rebuilds the read model while the live projector keeps running:
//  1. create order_summary_rebuild (LIKE order_summary) and replay the log up to
//     a fence into it;
//  2. catch-up passes, each up to a new fence;
//  3. in one transaction: LOCK received_events (blocks ApplyOnce, not readers of
//     the log), replay the final tail, swap the table names, commit. The RENAME
//     takes ACCESS EXCLUSIVE on order_summary, so readers wait for those last
//     milliseconds. Lock order matches ApplyOnce (log, then summary): no deadlock.
func RebuildAndSwap(ctx context.Context, db *pgxpool.Pool) error {
	if _, err := db.Exec(ctx, `DROP TABLE IF EXISTS order_summary_rebuild;
		CREATE TABLE order_summary_rebuild (LIKE order_summary INCLUDING ALL)`); err != nil {
		return err
	}
	live := Store{DB: db}
	target := Store{DB: db, Table: "order_summary_rebuild"}
	var last int64
	for i := 0; i < 4; i++ { // first pass + catch-up passes
		f, err := fence(ctx, db)
		if err != nil {
			return err
		}
		if _, err := readmodel.Rebuild(ctx, live, last, f, target); err != nil {
			return err
		}
		last = f // not the last row seen: rolled-back inserts leave gaps
	}
	return pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
		// EXCLUSIVE allows only ACCESS SHARE (plain SELECT) alongside it.
		if _, err := tx.Exec(ctx, `LOCK TABLE received_events IN EXCLUSIVE MODE`); err != nil {
			return err
		}
		tail, err := collectTail(ctx, tx, last) // complete: no inserter is open now
		if err != nil {
			return err
		}
		table := pgx.Identifier{"order_summary_rebuild"}.Sanitize()
		for _, env := range tail {
			patch, err := readmodel.Decode(env)
			if err != nil {
				return err
			}
			if patch != nil {
				if err := apply(ctx, tx, table, patch); err != nil {
					return err
				}
			}
		}
		_, err = tx.Exec(ctx, `
			ALTER TABLE order_summary RENAME TO order_summary_old;
			ALTER TABLE order_summary_rebuild RENAME TO order_summary;
			DROP TABLE order_summary_old`)
		return err
	})
}

// collectTail reads the rest of the log inside the locking transaction. Rows
// are collected first because one connection cannot Exec while rows are open.
func collectTail(ctx context.Context, tx pgx.Tx, after int64) ([]contracts.Envelope, error) {
	rows, err := tx.Query(ctx, `
		SELECT event_id, source, type, subject, source_version, occurred_at, payload
		FROM received_events WHERE position > $1 ORDER BY position`, after)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []contracts.Envelope
	for rows.Next() {
		var e contracts.Envelope
		if err := rows.Scan(&e.ID, &e.Source, &e.Type, &e.Subject, &e.SourceVersion, &e.Time, &e.Data); err != nil {
			return nil, err
		}
		out = append(out, e)
	}
	return out, rows.Err()
}

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

go
package readmodel

import (
	"context"
	"sync"

	"academy/microservices-data-patterns/contracts"
)

// Memory is an in-memory Store, Log and Target with the same contract as the
// PostgreSQL store; tests and the demo use it.
type Memory struct {
	mu   sync.Mutex
	rows map[string]OrderSummary
	seen map[string]bool
	log  []contracts.Envelope
}

// NewMemory returns an empty store.
func NewMemory() *Memory {
	return &Memory{rows: map[string]OrderSummary{}, seen: map[string]bool{}}
}

// ApplyOnce appends to the log and applies the patch atomically.
func (m *Memory) ApplyOnce(_ context.Context, env contracts.Envelope, p Patch) (bool, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.seen[env.ID] {
		return false, nil
	}
	m.seen[env.ID] = true
	m.log = append(m.log, env)
	m.apply(p)
	return true, nil
}

// Apply applies a patch without dedup (rebuild target).
func (m *Memory) Apply(_ context.Context, p Patch) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.apply(p)
	return nil
}

// apply mirrors the SQL upserts: create the row if missing, set only the
// columns the patch owns, guard the Sales columns by version.
func (m *Memory) apply(p Patch) {
	r := m.rows[p.orderID()]
	r.OrderID = p.orderID()
	switch v := p.(type) {
	case PlacedPatch:
		if v.SalesVersion <= r.SalesVersion {
			return // stale or replayed older Sales fact
		}
		at := v.PlacedAt
		r.CustomerID, r.Currency, r.TotalMinor, r.LineCount = v.CustomerID, v.Currency, v.TotalMinor, v.LineCount
		r.SalesVersion, r.PlacedAt = v.SalesVersion, &at
	case DispatchedPatch:
		at := v.DispatchedAt
		r.DispatchedAt, r.Carrier, r.TrackingRef = &at, v.Carrier, v.TrackingRef
	case PaidPatch:
		at := v.PaidAt
		r.PaidAt, r.PaidMinor = &at, v.PaidMinor
	}
	m.rows[r.OrderID] = r
}

// Get reads one row.
func (m *Memory) Get(_ context.Context, id string) (OrderSummary, bool, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	r, ok := m.rows[id]
	return r, ok, nil
}

// ReplayAfter walks positions after+1 .. upTo (positions start at 1; upTo 0 = all).
func (m *Memory) ReplayAfter(_ context.Context, after, upTo int64, fn func(int64, contracts.Envelope) error) (int64, error) {
	m.mu.Lock()
	log := append([]contracts.Envelope(nil), m.log...)
	m.mu.Unlock()
	end := len(log)
	if upTo > 0 && int(upTo) < end {
		end = int(upTo)
	}
	last := after
	for i := int(after); i < end; i++ {
		if err := fn(int64(i+1), log[i]); err != nil {
			return last, err
		}
		last = int64(i + 1)
	}
	return last, nil
}

Read-your-writes: صبر برای توکن نسخه ​

go
// Package query is the read API. WaitFor implements read-your-writes on an
// asynchronously updated read model: the client sends the version token it got
// from the command, and the query waits briefly for the projection to reach it.
package query

import (
	"context"
	"errors"
	"time"

	"academy/microservices-data-patterns/readmodel"
)

// ErrNotYetProjected tells the HTTP layer to answer 202 with Retry-After, or
// the UI to keep its optimistic copy.
var ErrNotYetProjected = errors.New("read model has not reached the requested version")

// Reader is the read store's query port.
type Reader interface {
	Get(ctx context.Context, orderID string) (readmodel.OrderSummary, bool, error)
}

// WaitFor polls until SalesVersion >= minVersion or the budget runs out.
// The budget stays small (a few hundred ms): this is a UX aid, not a lock.
func WaitFor(ctx context.Context, r Reader, orderID string, minVersion int64, budget, every time.Duration) (readmodel.OrderSummary, error) {
	deadline := time.Now().Add(budget)
	for {
		row, ok, err := r.Get(ctx, orderID)
		if err != nil {
			return readmodel.OrderSummary{}, err
		}
		if ok && row.SalesVersion >= minVersion {
			return row, nil
		}
		if time.Now().After(deadline) {
			return row, ErrNotYetProjected
		}
		select {
		case <-ctx.Done():
			return row, ctx.Err()
		case <-time.After(every):
		}
	}
}

یک demo قابل اجرا ​

go
// Command demo runs the write side and the projector in one process with the
// in-memory store: place an order, deliver three contexts' events out of order
// and twice, read with a version token, then rebuild and compare.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"academy/microservices-data-patterns/contracts"
	"academy/microservices-data-patterns/query"
	"academy/microservices-data-patterns/readmodel"
	"academy/microservices-data-patterns/sales"
)

type outbox struct{ events []contracts.Envelope }

// Add stands in for "INSERT order + INSERT outbox row" in one transaction.
func (o *outbox) Add(_ context.Context, _ *sales.Order, evs []sales.Placed) error {
	for _, e := range evs {
		env, err := contracts.New("evt-placed-"+e.OrderID, "/sales", contracts.TypeOrderPlacedV1, e.OrderID, e.At, e.Version,
			contracts.OrderPlacedV1{OrderID: e.OrderID, CustomerID: e.CustomerID, TotalMinor: e.TotalMinor, Currency: e.Currency, LineCount: e.LineCount})
		if err != nil {
			return err
		}
		o.events = append(o.events, env)
	}
	return nil
}

type printLag struct{}

func (printLag) Observe(src string, d time.Duration) { fmt.Printf("  lag %-11s %v\n", src, d) }

func main() {
	ctx := context.Background()
	t0 := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
	ob := &outbox{}
	h := sales.PlaceOrderHandler{Repo: ob, Now: func() time.Time { return t0 }}
	ack, err := h.Handle(ctx, sales.PlaceOrder{OrderID: "o-1", CustomerID: "c-9", Currency: "EUR",
		Lines: []sales.Line{{SKU: "MUG", Quantity: 2, PriceMinor: 1250}}})
	if err != nil {
		panic(err)
	}
	fmt.Printf("1 command acknowledged: order=%s version=%d\n", ack.OrderID, ack.Version)

	store := readmodel.NewMemory()
	p := &readmodel.Projector{Store: store, Lag: printLag{}, Now: func() time.Time { return t0.Add(4 * time.Minute) }}

	_, err = query.WaitFor(ctx, store, ack.OrderID, ack.Version, 20*time.Millisecond, 5*time.Millisecond)
	fmt.Printf("2 read before projection: %v\n", err)

	dispatched, _ := contracts.New("evt-ship-1", "/fulfilment", contracts.TypeParcelDispatchedV1, "o-1", t0.Add(3*time.Minute), 4,
		contracts.ParcelDispatchedV1{OrderID: "o-1", ShipmentID: "s-7", Carrier: "DHL", TrackingRef: "JD0042"})
	paid, _ := contracts.New("evt-paid-1", "/billing", contracts.TypeInvoicePaidV1, "o-1", t0.Add(time.Minute), 2,
		contracts.InvoicePaidV1{OrderID: "o-1", InvoiceID: "inv-3", PaidMinor: 2500})
	fmt.Println("3 deliveries: dispatched, dispatched (duplicate), placed, paid")
	for _, e := range []contracts.Envelope{dispatched, dispatched, ob.events[0], paid} {
		if err := p.Handle(ctx, e); err != nil {
			panic(err)
		}
	}

	row, err := query.WaitFor(ctx, store, ack.OrderID, ack.Version, 20*time.Millisecond, 5*time.Millisecond)
	if err != nil {
		panic(err)
	}
	b, _ := json.Marshal(row)
	fmt.Printf("4 read with token v%d: status=%s %s\n", ack.Version, row.Status(), b)

	fresh := readmodel.NewMemory()
	last, err := readmodel.Rebuild(ctx, store, 0, 0, fresh)
	if err != nil {
		panic(err)
	}
	rebuilt, _, _ := fresh.Get(ctx, "o-1")
	rb, _ := json.Marshal(rebuilt)
	fmt.Printf("5 rebuilt from %d logged events, identical=%v\n", last, string(rb) == string(b))
}

غلط: PUT در CRUD، پرس‌وجویی که CQS را می‌شکند، join میان schemaها ​

go
// Package wrong shows the two shapes this chapter argues against.
package wrong

import "database/sql"

// OrderDTO is the whole record, sent back and forth by a CRUD screen.
type OrderDTO struct {
	ID         string
	Status     string // the client may send "dispatched" directly
	TotalMinor int64
	Carrier    string
}

// SaveOrder is a CRUD "PUT": the intent (pay? dispatch? correct the address?) is
// lost, any field can be overwritten, and the rule "dispatch only when paid" has no
// place to live.
func SaveOrder(db *sql.DB, in OrderDTO) error {
	_, err := db.Exec(`UPDATE orders SET status=$2, total_minor=$3, carrier=$4 WHERE id=$1`,
		in.ID, in.Status, in.TotalMinor, in.Carrier)
	return err
}

// NextShipmentAndMark both answers a question and changes state (a CQS
// violation): calling it twice from a dashboard "just to look" marks two orders.
func NextShipmentAndMark(db *sql.DB) (string, error) {
	var id string
	err := db.QueryRow(`UPDATE orders SET status='picking'
		WHERE id = (SELECT id FROM orders WHERE status='paid' ORDER BY placed_at LIMIT 1)
		RETURNING id`).Scan(&id)
	return id, err
}

// SummaryByJoiningOtherServices joins tables that belong to Fulfilment and
// Billing: a shared database in disguise.
func SummaryByJoiningOtherServices(db *sql.DB, orderID string) (*sql.Row, error) {
	return db.QueryRow(`SELECT o.id, s.tracking_ref, i.paid_at
		FROM sales.orders o
		LEFT JOIN fulfilment.shipments s ON s.order_id = o.id
		LEFT JOIN billing.invoices i ON i.order_id = o.id
		WHERE o.id = $1`, orderID), nil
}

نگاه Go ​

  • pgx ("a pure Go driver and toolkit for PostgreSQL") تابع pgx.BeginFunc را برای dedup و upsert در یک تراکنش، CommandTag.RowsAffected() را برای تشخیص تکرار و pgx.Identifier{…}.Sanitize() را برای نام جدولی که rebuild در آن می‌نویسد می‌دهد.
  • sqlc ("sqlc generates fully type-safe idiomatic Go code from SQL") به لایهٔ خواندن نازک خوب می‌خورد: سمت خواندن SQL خالص است و متدهای تولیدشده آن را typed نگه می‌دارند. کد بالا دست‌نویس است؛ با sqlc upsertها را در فایل queries.sql می‌گذارید و متدهای تولیدشده را درون همان تراکنش صدا می‌زنید.
  • Watermill بستهٔ cqrs دارد ("We segregate the responsibility between commands (write requests) and queries (read requests)") با command bus، event bus و EventProcessor/NewEventHandler روی Kafka، RabbitMQ، SQL و غیره. مسیریابی و marshalling را انجام می‌دهد؛ idempotency و انبار خواندن همچنان کد شماست، دقیقاً مثل بالا.
  • interfaceهای Go انبار را قابل تعویض می‌کنند: همان Projector در تست روی readmodel.Memory و در production روی pgstore.Store اجرا می‌شود.
  • هم‌روندی projector را بر اساس کلید نگه دارید: یک goroutine برای هر partition (یا برای هر hash شناسهٔ سفارش) ترتیب هر سفارش را حفظ می‌کند و رقابت روی قفل سطر را حذف می‌کند.

Laravel ​

Laravel 13 و PHP 8.4. در modular monolith، relay مربوط به outbox رویداد IntegrationEventReceived را درون همان پردازه dispatch می‌کند؛ در شکل میکروسرویسی، consumer مربوط به broker در سرویس سمت خواندن هر پیام را با IntegrationEvent::fromArray decode می‌کند و همان رویداد را dispatch می‌کند. projector فرقش را نمی‌فهمد.

قراردادها ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Contracts;

use DateTimeImmutable;

/**
 * The envelope every context publishes (CloudEvents attribute names).
 * sourceVersion is the publishing aggregate's version after the change.
 */
final readonly class IntegrationEvent
{
    public const ORDER_PLACED_V1 = 'sales.order.placed.v1';
    public const PARCEL_DISPATCHED_V1 = 'fulfilment.parcel.dispatched.v1';
    public const INVOICE_PAID_V1 = 'billing.invoice.paid.v1';

    /** @param array<string, mixed> $data */
    public function __construct(
        public string $id,
        public string $source,
        public string $type,
        public string $subject,
        public DateTimeImmutable $time,
        public int $sourceVersion,
        public array $data,
    ) {
    }

    /** @param array<string, mixed> $row a received_events row or a decoded message body */
    public static function fromArray(array $row): self
    {
        return new self(
            id: (string) $row['id'],
            source: (string) $row['source'],
            type: (string) $row['type'],
            subject: (string) $row['subject'],
            time: new DateTimeImmutable((string) $row['time']),
            sourceVersion: (int) $row['sourceversion'],
            data: is_array($row['data']) ? $row['data'] : json_decode((string) $row['data'], true, flags: JSON_THROW_ON_ERROR),
        );
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Contracts;

use Illuminate\Foundation\Events\Dispatchable;

/**
 * Dispatched by whoever delivers integration events into this process:
 * - modular monolith: the outbox relay command, in-process;
 * - microservices: the broker consumer of the read-side service
 *   (RabbitMQ/Kafka message body decoded with IntegrationEvent::fromArray).
 */
final class IntegrationEventReceived
{
    use Dispatchable;

    public function __construct(public readonly IntegrationEvent $event)
    {
    }
}

سمت نوشتن: CQS روی aggregate، یک فرمان، یک action، یک endpoint مبتنی بر وظیفه ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use DateTimeImmutable;
use DomainException;

/**
 * Write model. Commands (place, markPaid, dispatch) change state and return
 * nothing; queries (status, version, total, canDispatch) return data and change
 * nothing. Screens never read this class: they read OrderSummary.
 */
final class Order
{
    /** @var list<array<string, mixed>> */
    private array $recorded = [];

    /** @param list<array{sku: string, quantity: int, price_minor: int}> $lines */
    private function __construct(
        public readonly string $id,
        private readonly string $customerId,
        private readonly array $lines,
        private readonly string $currency,
        private string $status,
        private int $version,
    ) {
    }

    /** @param list<array{sku: string, quantity: int, price_minor: int}> $lines */
    public static function place(string $id, string $customerId, string $currency, array $lines, DateTimeImmutable $now): self
    {
        if ($lines === []) {
            throw new DomainException('An order needs at least one line.');
        }
        $order = new self($id, $customerId, $lines, $currency, 'placed', 1);
        $order->recorded[] = [
            'type' => 'OrderPlaced',
            'order_id' => $id,
            'customer_id' => $customerId,
            'total_minor' => $order->total(),
            'currency' => $currency,
            'line_count' => count($lines),
            'version' => $order->version,
            'at' => $now->format(DATE_ATOM),
        ];

        return $order;
    }

    public function markPaid(): void
    {
        if ($this->status !== 'placed') {
            throw new DomainException('Only a placed order can be paid.');
        }
        $this->status = 'paid';
        $this->version++;
    }

    public function dispatch(): void
    {
        if (! $this->canDispatch()) {
            throw new DomainException('An unpaid order cannot be dispatched.');
        }
        $this->status = 'dispatched';
        $this->version++;
    }

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

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

    public function canDispatch(): bool
    {
        return $this->status === 'paid';
    }

    public function total(): int
    {
        return array_sum(array_map(fn (array $l): int => $l['quantity'] * $l['price_minor'], $this->lines));
    }

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

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

    /** @return list<array<string, mixed>> */
    public function pullEvents(): array
    {
        [$events, $this->recorded] = [$this->recorded, []];

        return $events;
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Application;

/** A command: an intent in the imperative, carrying only what the behaviour needs. */
final readonly class PlaceOrder
{
    /** @param list<array{sku: string, quantity: int, price_minor: int}> $lines */
    public function __construct(
        public string $orderId, // client-generated UUID
        public string $customerId,
        public string $currency,
        public array $lines,
    ) {
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Application;

use App\Modules\Contracts\IntegrationEvent;
use App\Modules\Sales\Domain\Order;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * The command handler ("action"). It writes the aggregate and the outbox row
 * in ONE transaction and returns only the new version: a consistency token,
 * not read data. The outbox relay (see the Outbox chapter) delivers the event.
 */
final class PlaceOrderAction
{
    public function __invoke(PlaceOrder $cmd): int
    {
        $order = Order::place($cmd->orderId, $cmd->customerId, $cmd->currency, $cmd->lines, new DateTimeImmutable());

        DB::transaction(function () use ($order): void {
            DB::table('sales_orders')->insert([
                'id' => $order->id,
                'customer_id' => $order->customerId(),
                'currency' => $order->currency(),
                'total_minor' => $order->total(),
                'status' => $order->status(),
                'version' => $order->version(),
            ]);

            foreach ($order->pullEvents() as $e) {
                DB::table('sales_outbox')->insert([
                    'id' => (string) Str::uuid7(),
                    'type' => IntegrationEvent::ORDER_PLACED_V1,
                    'subject' => $e['order_id'],
                    'source_version' => $e['version'],
                    'occurred_at' => $e['at'],
                    'payload' => json_encode([
                        'orderId' => $e['order_id'],
                        'customerId' => $e['customer_id'],
                        'totalMinor' => $e['total_minor'],
                        'currency' => $e['currency'],
                        'lineCount' => $e['line_count'],
                    ], JSON_THROW_ON_ERROR),
                ]);
            }
        });

        return $order->version();
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Http;

use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlaceOrderAction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Task-based endpoint: POST /orders (place), not PUT /orders/{id} with the
 * whole record. The response carries a version token and where to read.
 */
final class OrderCommandController
{
    public function place(Request $request, PlaceOrderAction $placeOrder): JsonResponse
    {
        $valid = $request->validate([
            'order_id' => ['required', 'uuid'],
            'currency' => ['required', 'string', 'size:3'],
            'lines' => ['required', 'array', 'min:1'],
            'lines.*.sku' => ['required', 'string'],
            'lines.*.quantity' => ['required', 'integer', 'min:1'],
            'lines.*.price_minor' => ['required', 'integer', 'min:0'],
        ]);

        $version = $placeOrder(new PlaceOrder(
            orderId: $valid['order_id'],
            customerId: (string) $request->user()->getAuthIdentifier(),
            currency: $valid['currency'],
            lines: $valid['lines'],
        ));

        $readUrl = route('order-summaries.show', ['orderId' => $valid['order_id'], 'min_version' => $version]);

        return response()->json(['order_id' => $valid['order_id'], 'version' => $version], 202)
            ->header('Location', $readUrl);
    }
}

جدول read model و log ​

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 = 'read_model';

    public function up(): void
    {
        Schema::create('received_events', function (Blueprint $table): void {
            $table->id('position');                 // replay order
            $table->string('event_id')->unique();   // idempotency key
            $table->string('source');
            $table->string('type');
            $table->string('subject')->index();
            $table->unsignedBigInteger('source_version');
            $table->timestampTz('occurred_at');
            $table->timestampTz('received_at')->useCurrent();
            $table->jsonb('payload');
        });

        Schema::create('order_summary', function (Blueprint $table): void {
            $table->string('order_id')->primary();
            // Sales columns
            $table->string('customer_id')->nullable();
            $table->char('currency', 3)->nullable();
            $table->bigInteger('total_minor')->default(0);
            $table->integer('line_count')->default(0);
            $table->unsignedBigInteger('sales_version')->default(0);
            $table->timestampTz('placed_at')->nullable();
            // Fulfilment columns
            $table->timestampTz('dispatched_at')->nullable();
            $table->string('carrier')->nullable();
            $table->string('tracking_ref')->nullable();
            // Billing columns
            $table->timestampTz('paid_at')->nullable();
            $table->bigInteger('paid_minor')->default(0);
            $table->timestampTz('updated_at')->useCurrent();

            $table->index(['customer_id', 'placed_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('order_summary');
        Schema::dropIfExists('received_events');
    }
};
php
<?php

declare(strict_types=1);

namespace App\Modules\OrderSummary;

use Illuminate\Database\Eloquent\Model;

/**
 * Read model row. Read-only for everything except the projector.
 * It lives on its own connection so a read/write split elsewhere does not
 * add a second, invisible lag on top of the projection lag.
 */
final class OrderSummary extends Model
{
    protected $connection = 'read_model';
    protected $table = 'order_summary';
    protected $primaryKey = 'order_id';
    protected $keyType = 'string';
    public $incrementing = false;
    public $timestamps = false; // the projector sets updated_at itself
    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'placed_at' => 'immutable_datetime',
            'dispatched_at' => 'immutable_datetime',
            'paid_at' => 'immutable_datetime',
            'sales_version' => 'integer',
            'total_minor' => 'integer',
            'paid_minor' => 'integer',
        ];
    }

    /** Status is derived from which facts arrived, so arrival order does not matter. */
    public function status(): string
    {
        return match (true) {
            $this->placed_at === null => 'pending',
            $this->dispatched_at !== null && $this->paid_at !== null => 'completed',
            $this->dispatched_at !== null => 'dispatched',
            $this->paid_at !== null => 'paid',
            default => 'placed',
        };
    }
}

projector و listener صف‌شده: dedup با insertOrIgnore، patch با whereKey ​

php
<?php

declare(strict_types=1);

namespace App\Modules\OrderSummary;

use App\Modules\Contracts\IntegrationEvent;
use Illuminate\Database\Eloquent\Builder;

/**
 * Pure projection logic: one event in, one row patched. No dedup here; the
 * listener (live) and the log (rebuild) provide it. Each event type writes
 * ONLY the columns its context owns.
 */
final class OrderSummaryProjector
{
    public function __construct(private readonly string $table = 'order_summary')
    {
    }

    public function handles(string $type): bool
    {
        return in_array($type, [
            IntegrationEvent::ORDER_PLACED_V1,
            IntegrationEvent::PARCEL_DISPATCHED_V1,
            IntegrationEvent::INVOICE_PAID_V1,
        ], true);
    }

    public function apply(IntegrationEvent $e): void
    {
        if (! $this->handles($e->type)) {
            return; // unknown or newer types are ignored, not fatal
        }

        // The row may not exist yet: ParcelDispatched can arrive before OrderPlaced.
        $this->rows()->insertOrIgnore(['order_id' => $e->subject, 'updated_at' => now()]);

        $d = $e->data;
        match ($e->type) {
            IntegrationEvent::ORDER_PLACED_V1 => $this->rows()
                ->whereKey($e->subject)
                ->where('sales_version', '<', $e->sourceVersion) // stale Sales facts lose
                ->update([
                    'customer_id' => $d['customerId'],
                    'currency' => $d['currency'],
                    'total_minor' => $d['totalMinor'],
                    'line_count' => $d['lineCount'],
                    'sales_version' => $e->sourceVersion,
                    'placed_at' => $e->time,
                    'updated_at' => now(),
                ]),
            IntegrationEvent::PARCEL_DISPATCHED_V1 => $this->rows()
                ->whereKey($e->subject)
                ->update([
                    'dispatched_at' => $e->time,
                    'carrier' => $d['carrier'],
                    'tracking_ref' => $d['trackingRef'],
                    'updated_at' => now(),
                ]),
            IntegrationEvent::INVOICE_PAID_V1 => $this->rows()
                ->whereKey($e->subject)
                ->update([
                    'paid_at' => $e->time,
                    'paid_minor' => $d['paidMinor'],
                    'updated_at' => now(),
                ]),
        };
    }

    /** @return Builder<OrderSummary> */
    private function rows(): Builder
    {
        return (new OrderSummary())->setTable($this->table)->newQuery();
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\OrderSummary;

use App\Modules\Contracts\IntegrationEventReceived;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Queued projection handler. Register it in a module service provider:
 * Event::listen(IntegrationEventReceived::class, ProjectOrderSummary::class);
 *
 * Idempotency: the event id goes into received_events (UNIQUE event_id) in
 * the same transaction as the row patch. A redelivery inserts 0 rows and stops.
 */
final class ProjectOrderSummary implements ShouldQueueAfterCommit
{
    use InteractsWithQueue;

    public string $queue = 'projections';

    public int $tries = 10;

    public function __construct(private readonly OrderSummaryProjector $projector)
    {
    }

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

    public function handle(IntegrationEventReceived $received): void
    {
        $e = $received->event;
        if (! $this->projector->handles($e->type)) {
            return;
        }

        $applied = DB::connection('read_model')->transaction(function () use ($e): bool {
            $inserted = DB::connection('read_model')->table('received_events')->insertOrIgnore([
                'event_id' => $e->id,
                'source' => $e->source,
                'type' => $e->type,
                'subject' => $e->subject,
                'source_version' => $e->sourceVersion,
                'occurred_at' => $e->time,
                'payload' => json_encode($e->data, JSON_THROW_ON_ERROR),
            ]);
            if ($inserted === 0) {
                return false; // duplicate delivery
            }
            $this->projector->apply($e);

            return true;
        });

        if ($applied) {
            // Projection lag: now minus the event's own time. Export it as a metric.
            Log::info('projection.applied', [
                'projection' => 'order_summary',
                'source' => $e->source,
                'lag_ms' => (int) ((microtime(true) - (float) $e->time->format('U.u')) * 1000),
            ]);
        }
    }
}

فرمان بازسازی ​

php
<?php

declare(strict_types=1);

namespace App\Modules\OrderSummary;

use App\Modules\Contracts\IntegrationEvent;
use Illuminate\Console\Command;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;

/**
 * php artisan order-summary:rebuild
 *
 * Replays received_events into order_summary_rebuild while the live projector
 * keeps running, catches up, then swaps tables under a short lock (PostgreSQL).
 * Positions are assigned at INSERT, not COMMIT, so every pass replays only up
 * to a fence read under LOCK ... EXCLUSIVE (all earlier inserts have committed).
 */
final class RebuildOrderSummaries extends Command
{
    protected $signature = 'order-summary:rebuild {--chunk=1000}';

    protected $description = 'Rebuild the OrderSummary read model from the received-events log';

    public function handle(): int
    {
        $db = DB::connection('read_model');
        $db->statement('DROP TABLE IF EXISTS order_summary_rebuild');
        $db->statement('CREATE TABLE order_summary_rebuild (LIKE order_summary INCLUDING ALL)');

        $projector = new OrderSummaryProjector('order_summary_rebuild');
        $last = 0;
        for ($pass = 0; $pass < 4; $pass++) { // first pass + catch-up passes
            $fence = $this->fence($db);
            $this->replay($db, $projector, $last, $fence);
            $last = $fence; // not the last row seen: rolled-back inserts leave gaps
        }
        $this->info("replayed up to position {$last}");

        $db->transaction(function () use ($db, $projector, $last): void {
            // Blocks new inserts into the log (live listener) but not plain SELECTs.
            $db->statement('LOCK TABLE received_events IN EXCLUSIVE MODE');
            $this->replay($db, $projector, $last, null); // complete: no inserter is open
            // RENAME takes ACCESS EXCLUSIVE: readers of order_summary wait until COMMIT.
            $db->statement('ALTER TABLE order_summary RENAME TO order_summary_old');
            $db->statement('ALTER TABLE order_summary_rebuild RENAME TO order_summary');
            $db->statement('DROP TABLE order_summary_old');
        });

        $this->info('swapped');

        return self::SUCCESS;
    }

    /** A position below which every log insert has committed. */
    private function fence(ConnectionInterface $db): int
    {
        return (int) $db->transaction(function () use ($db): int {
            $db->statement('LOCK TABLE received_events IN EXCLUSIVE MODE');

            return (int) $db->table('received_events')->max('position');
        });
    }

    private function replay(ConnectionInterface $db, OrderSummaryProjector $projector, int $after, ?int $upTo): int
    {
        $last = $after;
        $db->table('received_events')
            ->where('position', '>', $after)
            ->when($upTo !== null, fn ($q) => $q->where('position', '<=', $upTo))
            ->lazyById((int) $this->option('chunk'), 'position')
            ->each(function (object $row) use ($projector, &$last): void {
                $projector->apply(IntegrationEvent::fromArray([
                    'id' => $row->event_id,
                    'source' => $row->source,
                    'type' => $row->type,
                    'subject' => $row->subject,
                    'time' => $row->occurred_at,
                    'sourceversion' => $row->source_version,
                    'data' => $row->payload,
                ]));
                $last = (int) $row->position;
            });

        return $last;
    }
}

endpoint پرس‌وجو با توکن نسخه ​

php
<?php

declare(strict_types=1);

namespace App\Modules\OrderSummary;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * GET /order-summaries/{orderId}?min_version=1
 * Read-your-writes on an async read model: wait briefly for the projection
 * to reach the version the command returned, else answer 202 + Retry-After.
 */
final class OrderSummaryController
{
    public function show(Request $request, string $orderId): JsonResponse
    {
        $minVersion = (int) $request->query('min_version', '0');
        $deadline = microtime(true) + 0.3; // a UX budget, not a lock

        do {
            $row = OrderSummary::query()->whereKey($orderId)->first();
            if ($row !== null && $row->sales_version >= $minVersion) {
                return response()->json([
                    'order_id' => $row->order_id,
                    'status' => $row->status(),
                    'total_minor' => $row->total_minor,
                    'currency' => $row->currency,
                    'carrier' => $row->carrier,
                    'tracking_ref' => $row->tracking_ref,
                    'sales_version' => $row->sales_version,
                ]);
            }
            usleep(50_000);
        } while (microtime(true) < $deadline);

        return response()->json(['order_id' => $orderId, 'status' => 'processing'], 202)
            ->header('Retry-After', '1');
    }
}

تست‌های Pest: replay fixture، تکرار، pending، بازسازی، snapshot ​

php
<?php

declare(strict_types=1);

use App\Modules\Contracts\IntegrationEvent;
use App\Modules\Contracts\IntegrationEventReceived;
use App\Modules\OrderSummary\OrderSummary;
use App\Modules\OrderSummary\ProjectOrderSummary;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

// Runs on PostgreSQL (the rebuild uses CREATE TABLE ... LIKE and LOCK TABLE);
// phpunit.xml points the read_model connection at the test database.
uses(RefreshDatabase::class);

/** Replay fixture: three contexts, delivered out of order (dispatched first). */
function fixture(): array
{
    $e = fn (string $id, string $src, string $type, string $at, int $v, array $data) => new IntegrationEvent(
        $id, $src, $type, 'o-1', new DateTimeImmutable($at), $v, $data,
    );

    return [
        $e('evt-ship-1', '/fulfilment', IntegrationEvent::PARCEL_DISPATCHED_V1, '2026-11-25T10:03:00Z', 4,
            ['orderId' => 'o-1', 'carrier' => 'DHL', 'trackingRef' => 'JD0042']),
        $e('evt-placed-1', '/sales', IntegrationEvent::ORDER_PLACED_V1, '2026-11-25T10:00:00Z', 1,
            ['orderId' => 'o-1', 'customerId' => 'c-9', 'totalMinor' => 2500, 'currency' => 'EUR', 'lineCount' => 1]),
        $e('evt-paid-1', '/billing', IntegrationEvent::INVOICE_PAID_V1, '2026-11-25T10:01:00Z', 2,
            ['orderId' => 'o-1', 'paidMinor' => 2500]),
    ];
}

function project(array $events): void
{
    $listener = app(ProjectOrderSummary::class);
    foreach ($events as $event) {
        $listener->handle(new IntegrationEventReceived($event));
    }
}

it('converges whatever the arrival order', function () {
    project(fixture());

    $row = OrderSummary::query()->whereKey('o-1')->firstOrFail();
    expect($row->status())->toBe('completed')
        ->and($row->total_minor)->toBe(2500)
        ->and($row->carrier)->toBe('DHL');
});

it('ignores a duplicate delivery', function () {
    project([...fixture(), ...fixture()]);

    expect(DB::connection('read_model')->table('received_events')->count())->toBe(3);
});

it('shows pending when only a downstream fact has arrived', function () {
    project([fixture()[0]]);

    expect(OrderSummary::query()->whereKey('o-1')->firstOrFail()->status())->toBe('pending');
});

it('rebuilds to the same row', function () {
    project(fixture());
    $before = OrderSummary::query()->whereKey('o-1')->firstOrFail()->toArray();

    $this->artisan('order-summary:rebuild')->assertSuccessful();

    $after = OrderSummary::query()->whereKey('o-1')->firstOrFail()->toArray();
    expect(collect($after)->except('updated_at')->all())
        ->toBe(collect($before)->except('updated_at')->all());
});

it('matches the snapshot', function () {
    project(fixture());

    $row = OrderSummary::query()->whereKey('o-1')->firstOrFail();
    expect(collect($row->toArray())->except('updated_at')->put('status', $row->status())->toJson(JSON_PRETTY_PRINT))
        ->toMatchSnapshot(); // pest-plugin-snapshots style golden file
});

غلط: controller در سبک CRUD و join میان contextها ​

php
<?php

declare(strict_types=1);

namespace App\Wrong;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Anti-patterns this chapter replaces:
 * 1. PUT the whole record: intent is lost, any field can be overwritten.
 * 2. The "summary" joins Fulfilment's and Billing's tables directly.
 */
final class OrderCrudController
{
    public function update(Request $request, string $id): JsonResponse
    {
        DB::table('orders')->where('id', $id)->update($request->only('status', 'total_minor', 'carrier'));

        return response()->json(DB::table('orders')->find($id)); // a query riding on a command
    }

    public function summary(string $id): JsonResponse
    {
        return response()->json(DB::table('sales.orders as o')
            ->leftJoin('fulfilment.shipments as s', 's.order_id', '=', 'o.id')
            ->leftJoin('billing.invoices as i', 'i.order_id', '=', 'o.id')
            ->where('o.id', $id)
            ->first(['o.id', 's.tracking_ref', 'i.paid_at']));
    }
}

نگاه Laravel ​

  • listener صف‌شده و تراکنش. مستندات هشدار می‌دهند listenerهای صف‌شده‌ای که درون تراکنش dispatch می‌شوند "may be processed by the queue before the database transaction has committed". ShouldQueueAfterCommit روی listener (یا after_commit روی اتصال صف) نمی‌گذارد projector سطرهایی را بخواند که هنوز وجود ندارند. این کار تحویل را دقیقاً یک‌بار نمی‌کند؛ کلید یکتای received_events می‌کند.
  • insertOrIgnore تعداد سطرهای درج‌شده را برمی‌گرداند و همین بررسی تکرار است؛ مستندات می‌گویند خطای رکورد تکراری را نادیده می‌گیرد (و روی MySQL حالت strict را دور می‌زند، پس اول payload را validate کنید).
  • whereKey (در Eloquent builder) سطر خواندنی را با کلید اصلی هدف می‌گیرد؛ همراه where('sales_version', '<', …) همان version guard است.
  • تفکیک خواندن/نوشتن. sticky در یک درخواست روی setup با replica خواندنِ نوشتهٔ خود را می‌دهد، که تأخیری متفاوت از تأخیر projection است؛ read model را روی اتصال جدای read_model گذاشته‌ایم تا این دو بی‌صدا روی هم جمع نشوند.
  • Scout: "Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records." برای index کردن مدل یک صاحب خوب است، نه برای read modelی که سه صاحب را join می‌کند (به‌جایش از projector یک engine یا index سفارشی را پر کنید).
  • کشف خودکار event به‌طور پیش‌فرض فقط پوشهٔ app/Listeners را می‌گردد؛ listenerهای ماژول را با Event::listen در service provider ماژول ثبت کنید.
  • ShouldBeUnique جلوی دو نسخه از یک job در صف را می‌گیرد؛ dedup event نیست و قفلش مدت انقضا دارد.

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

«این صفحه از سه سرویس داده می‌خواهد» ​

راه‌حلچطورمزیتهزینه / محدودیت
API compositionBFF هم‌زمان Sales، Fulfilment و Billing را صدا می‌زند و در حافظه join می‌کنددادهٔ زنده، بدون انبار تازهتأخیرِ کندترین، جواب ناقص، بدون فیلتر چندصاحبه
Read model (OrderSummary)eventهای سه context را در یک جدول project کنیک query سریع، فیلتر و صفحه‌بندیتأخیر، projector، log بازپخش، ابزار بازسازی
join روی دیتابیس مشترکJOIN میان schemaهاامروز آسان استschema سه تیم را به هم می‌دوزد؛ ممنوع
از Sales بخواه دادهٔ Billing را در مدل خودش نگه داردSales به InvoicePaid گوش می‌دهد و orders.paid_at را به‌روز می‌کندسرویس تازه لازم نیستمدل نوشتن Sales حالا واقعیت‌های دیگران را حمل می‌کند؛ فقط به‌عنوان نسخهٔ محلی کوچک قابل‌قبول است

ترجیح: composition برای صفحهٔ جزئیات سفارش؛ OrderSummary برای فهرست. کد در Go و Laravel است.

«فهرست هنوز وضعیت قدیمی را نشان می‌دهد» ​

راه‌حلچطورمزیتهزینه / محدودیت
توکن نسخه + صبرفرمان version برمی‌گرداند، پرس‌وجو min_version می‌گیردبرای عامل دقیق استتوکن باید همراه کلاینت برود
خوش‌بینی UIکلاینت سطر خودش را با برچسب «در حال پردازش» درج می‌کندفوریباید هماهنگ کند و رد شدن را مدیریت کند
زمان «به‌روز تا»نشان بده سطر آخرین بار کی به‌روز شدهصادقانهکاربر هنوز دادهٔ کهنه می‌بیند
projection هم‌زمانجدول خواندن را در تراکنش فرمان به‌روز کنهرگز کهنه نیستفقط در همان دیتابیس؛ نوشتن کندتر

«آیتم حذف‌شده هنوز در جست‌وجو هست» ​

راه‌حلچطورمزیتهزینه / محدودیت
حذف به‌شکل eventProductDeleted مثل هر event دیگری project شودهمان لولههرگز نباید دور ریخته شود
سنگ‌قبر + version guarddeleted_at و version را نگه دار؛ فقط eventهای تازه‌تر را اعمال کنجلوی رستاخیز را می‌گیردسنگ‌قبرها پاک‌سازی دوره‌ای می‌خواهند
external versioning در indexversion_type=external در Elasticsearch/OpenSearchindex نوشتن‌های قدیمی‌تر را رد می‌کندوابسته به محصول
فیلتر سخت هنگام پرس‌وجوبرای حذف‌های حساس از صاحب بپرسبرای حذف‌های حقوقی درست استیک فراخوانی برای هر صفحهٔ نتیجه

«شکل read model را عوض کرده‌ایم» ​

راه‌حلچطورمزیتهزینه / محدودیت
بازسازی و جایگزینیlog را تا حصارها در _rebuild بازپخش کن، جبران کن، تغییر نام بدهخواننده‌ها فقط برای تغییر نام صبر می‌کنندlog کامل لازم است؛ منطق حصار
v2 کنار v1projector تازه در order_summary_v2 می‌نویسد؛ خواننده‌ها با flag سوییچ می‌کنندبازگشت با برگرداندن flagمدتی دو projector
migration درجاALTER TABLE + backfill از logبرای ستون اضافه ساده استبرای تغییر معنایی پرخطر

«projector عقب افتاد، یا یک روز اشتباه کار کرد» ​

راه‌حلچطورمزیتهزینه / محدودیت
Catch-upاز آخرین موقعیت commitشده دوباره شروع کن؛ retention در broker فاصله را پوشش می‌دهدخودکارجهش تأخیر، retention باید ≥ مدت قطعی باشد
scale بر اساس کلیدpartition/worker بیشتر، کلید = شناسهٔ سفارشthroughput را برمی‌گرداندrebalance؛ ترتیب فقط برای هر کلید
بازسازی از logorder-summary:rebuild بعد از رفع باگهمهٔ سطرها را درست می‌کندمدتش با log رشد می‌کند؛ برای تاریخچهٔ خیلی بزرگ از log snapshot بگیرید
dead-letter برای eventهای سمیتلاش دوباره با backoff، بعد DLQ (DLQ)جریان ادامه پیدا می‌کندکسی باید DLQ را پردازش کند

«مالی می‌خواهد همه‌چیز را join کند» ​

راه‌حلچطورمزیتهزینه / محدودیت
warehouse با CDC/eventDebezium یا تاپیک‌های event به یک warehouseبدون بار روی سرویس‌ها؛ دادهٔ مدل‌شدهچند دقیقه تأخیر؛ یک تیم داده
دیتابیس گزارش (Fowler)نسخهٔ شبانه با شکل مناسب گزارشسادهدادهٔ دیروز
وصل کردن BI به replicaهاquery مستقیمهیچ‌کدام ماندگار نیستبا تغییر نام می‌شکند؛ تعارض replay

انتخاب ​

وضعیتتوصیهتکنیک اضافهدلیل
context با شکل CRUD (کاربران Identity، مدیریت Catalog)فقط CQS (قدم ۱)endpointهای مبتنی بر وظیفه برای معدود کارهای واقعیFowler: سیستم‌های CRUD "should be done in that style"
یک صاحب، شکل خواندن و نوشتن متفاوتCQRS قدم ۲ یا ۳ (لایهٔ خواندن نازک، جدول خواندنی در همان دیتابیس)projection هم‌زمانبدون تأخیر، بدون زیرساخت تازه
صفحهٔ جزئیات کلیددار میان صاحبانAPI compositionفراخوانی batch، timeout، جواب ناقصتازه، ساده
فهرست/فیلتر/صفحه‌بندی میان صاحبانread model مبتنی بر event (قدم ۴)log برای dedup، upsert، version guard، توکنفقط نسخهٔ محلی می‌تواند روی فیلد دیگران فیلتر کند
جست‌وجوی متنیsearch index که با event یا CDC پر می‌شودسنگ‌قبر، external versionSQL موتور مناسبی نیست
صاحب هنوز نمی‌تواند event منتشر کندCDC (Debezium) یا logical replication یک جدول قراردادیجدول outbox به‌عنوان منبع CDCمالکیت با یک جدول منتشرشده حفظ می‌شود
گزارش روی همه‌چیزwarehouse با CDC/eventmartهای مدل‌شدهتحلیل را از production دور نگه می‌دارد
ممیزی هر تغییر الزام استevent sourcing را برای همان context در نظر بگیریدprojection برای هر خواندنتاریخچه بنا به ساختار
مقیاس خواندن برای دادهٔ خود یک صاحبread replicasticky، محافظ تأخیرهمان مدل، خوانندهٔ بیشتر
گزارش درون یک دیتابیس در modular monolithmaterialized viewREFRESH … CONCURRENTLY زمان‌بندی‌شدهارزان‌ترین؛ کهنگی قابل‌قبول

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

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

همه‌چیز یک schema و یک تراکنش است، پس بیشتر این صفحه به CQS و حداکثر قدم ۲ از CQRS خلاصه می‌شود. مثال ساده: کلاس OrderQueries با SQL برای صفحهٔ «سفارش‌های من» کنار PlaceOrderAction؛ هر دو از همان جدول‌ها استفاده می‌کنند و تأخیری نیست. مثال پیچیده: query کند داشبورد به جدول خواندنی منتقل می‌شود که در همان تراکنش سفارش به‌روز می‌شود (قدم ۳)، یا به materialized viewی که هر پنج دقیقه تازه می‌شود. فرمان‌ها فقط version برگردانند تا کد برای قدم ۴ آماده باشد.

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

ماژول‌ها صاحب schemaها هستند (sales، fulfilment، billing) و نمی‌توانند جدول‌های هم را join کنند؛ هر ماژول دادهٔ ماژول دیگر را از API عمومی‌اش (درون پردازه) یا از eventها می‌خواند. مثال ساده: سمت خواندن OrderSummary در ماژول Sales به رویداد درون‌پردازه‌ای IntegrationEventReceived گوش می‌دهد که relay مربوط به outbox dispatch می‌کند؛ listener صف‌شده و جدول received_events همان کدی هستند که در میکروسرویس اجرا می‌شود. مثال پیچیده: یک schema گزارش با materialized viewهای میان‌ماژولی به‌عنوان قرارداد فقط‌خواندنی و متعلق به تیم گزارش تحمل می‌شود، با تست‌هایی که اگر ماژولی ستون مورد استفادهٔ view را تغییر نام دهد شکست می‌خورند؛ وقتی ماژول‌ها سرویس شوند حذف می‌شود.

میکروسرویس (Microservices): نه join، نه تراکنش مشترک ​

هر سرویس دیتابیس خودش را دارد؛ پرس‌وجوی میان صاحبان با composition یا read model انجام می‌شود؛ نوشتن با saga و outbox. جریان نمونه برای «سفارش‌های من»:

text
1    Client -> Sales: POST /orders {order_id: o-1}            -> COMMIT orders + sales_outbox
2    Sales relay -> broker: sales.order.placed.v1 (key o-1)    <- 202 {version: 1}
3    Billing consumes OrderPlaced, creates invoice; payment -> billing.invoice.paid.v1
4    Fulfilment consumes InvoicePaid, dispatches -> fulfilment.parcel.dispatched.v1
5    Read-side service consumes all three: received_events + order_summary (one tx each)
6    Client -> Read side: GET /order-summaries/o-1?min_version=1 -> 200 {status: completed}

هر پیکان حداقل یک‌بار است؛ هر consumer idempotent است؛ سمت خواندن صاحب انبار و log بازپخش خودش است، چون برای بازسازی اجازهٔ خواندن دیتابیس Sales، Fulfilment یا Billing را ندارد.

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

حالا تأخیرها روی هم جمع می‌شوند: تأخیر replica صاحب، فاصلهٔ relay، تأخیر broker، تأخیر projector و replication خود انبار خواندن. مثال: دیتابیس خواندن برای ترافیک سنگین فهرست یک replica دارد؛ بررسی توکن روی replica ممکن است شکست بخورد در حالی که primary سطر را دارد، پس وقتی min_version آمده پرس‌وجو از primary می‌خواند (یا صبر می‌کند). چند region: در هر region از روی یک تاپیک replicateشده در یک انبار خواندن project کنید؛ توکن نسخه همچنان کار می‌کند چون version aggregate را مقایسه می‌کند، نه زمان ساعت دیواری را. slotهای CDC و subscriptionهای logical replication باید در هر region پایش شوند (WAL نگه‌داشته‌شده).

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

بارسمت نوشتنسمت خواندنچه عوض می‌شود
1× (چند صد سفارش در روز)monolith، یک دیتابیسquery در SQL، CQSچیزی برای project کردن نیست
10×سرویس یا ماژول با outboxیک جدول OrderSummary، یک projector، خواندن با توکنmetric تأخیر و فرمان بازسازی پیدا می‌شوند
100×تاپیک‌های partitionشده بر اساس شناسهٔ سفارشworkerهای projector برای هر partition، replica برای انبار خواندن، search index، warehouseزمان بازسازی قید طراحی می‌شود: از log snapshot بگیرید و بر اساس بازهٔ کلید موازی بازسازی کنید

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

بخش ۱ روی هر ماشینی که Go دارد اجرا می‌شود (ما اجرایش کردیم و خروجی واقعی است). بخش‌های ۲ و ۳ به PostgreSQL و یک اپ Laravel نیاز دارند و با فرمان‌ها و خروجی مورد انتظار، اجرا نشده نوشته شده‌اند (قاعدهٔ هزینهٔ آزمایشگاه: بدون container).

۱. projector در حافظه (اجراشده).

bash
cd docs/snippets/ddd/microservices-data-patterns/go
go test ./readmodel ./query -v | grep -E '^--- |^ok'
go run ./cmd/demo
text
--- PASS: TestOutOfOrderEventsConverge (0.00s)
--- PASS: TestDispatchedBeforePlacedIsPending (0.00s)
--- PASS: TestDuplicateDeliveryIsANoOp (0.00s)
--- PASS: TestStaleSalesVersionIsIgnored (0.00s)
--- PASS: TestUnknownTypeIsIgnored (0.00s)
--- PASS: TestRebuildEqualsLive (0.00s)
--- PASS: TestSnapshot (0.00s)
ok   academy/microservices-data-patterns/readmodel
--- PASS: TestWaitForCatchesUp (0.00s)
--- PASS: TestWaitForGivesUp (0.01s)
ok   academy/microservices-data-patterns/query

1 command acknowledged: order=o-1 version=1
2 read before projection: read model has not reached the requested version
3 deliveries: dispatched, dispatched (duplicate), placed, paid
  lag /fulfilment 1m0s
  lag /sales      4m0s
  lag /billing    3m0s
4 read with token v1: status=completed {"orderId":"o-1",...,"salesVersion":1,...,"paidMinor":2500}
5 rebuilt from 3 logged events, identical=true

سطر ۲ همان خواندن ساده‌لوحانه است که شکست می‌خورد؛ سطر ۳ نشان می‌دهد تکرار جذب شده (سه سطر تأخیر برای چهار تحویل)؛ سطر ۵ ویژگی بازسازی است. حالا خرابش کنید: در readmodel/memory.go بررسی if m.seen[env.ID] را حذف کنید و go test ./readmodel را دوباره اجرا کنید: TestDuplicateDeliveryIsANoOp با want 3 applied, got 4 شکست می‌خورد. guard مربوط به v.SalesVersion <= r.SalesVersion را حذف کنید: TestStaleSalesVersionIsIgnored شکست می‌خورد.

۲. همان قاعده‌ها در PostgreSQL (مورد انتظار، اجرا نشده). schema را از سازوکار بسازید و بعد در دو session از psql:

sql
-- Session A: a delivery
BEGIN;
INSERT INTO received_events (event_id, source, type, subject, source_version, occurred_at, payload)
VALUES ('evt-ship-1', '/fulfilment', 'fulfilment.parcel.dispatched.v1', 'o-1', 4, now(), '{}')
ON CONFLICT (event_id) DO NOTHING;                 -- INSERT 0 1
INSERT INTO order_summary (order_id, dispatched_at, carrier) VALUES ('o-1', now(), 'DHL')
ON CONFLICT (order_id) DO UPDATE SET dispatched_at = EXCLUDED.dispatched_at, carrier = EXCLUDED.carrier;
COMMIT;
-- Session A again: the redelivery
INSERT INTO received_events (event_id, source, type, subject, source_version, occurred_at, payload)
VALUES ('evt-ship-1', '/fulfilment', 'fulfilment.parcel.dispatched.v1', 'o-1', 4, now(), '{}')
ON CONFLICT (event_id) DO NOTHING;                 -- INSERT 0 0  -> stop, do not touch order_summary
-- Without ON CONFLICT:
-- ERROR:  duplicate key value violates unique constraint "received_events_event_id_key"
SELECT order_id, placed_at IS NULL AS pending, carrier FROM order_summary;
--  order_id | pending | carrier
--  o-1      | t       | DHL

۳. materialized view در برابر projection (مورد انتظار، اجرا نشده). در یک دیتابیس با sales.orders، fulfilment.shipments و billing.invoices view گزینهٔ A را بسازید. یک ارسال درج کنید، بعد:

sql
SELECT carrier FROM reporting.order_summary_mv WHERE order_id = 'o-2';   -- (0 rows): not refreshed yet
REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.order_summary_mv;
SELECT carrier FROM reporting.order_summary_mv WHERE order_id = 'o-2';   -- DHL
DROP INDEX reporting.order_summary_mv_order_id_idx;
REFRESH MATERIALIZED VIEW CONCURRENTLY reporting.order_summary_mv;
-- ERROR:  cannot refresh materialized view "reporting.order_summary_mv" concurrently
-- HINT:  Create a unique index with no WHERE clause on one or more columns of the materialized view.

۴. Laravel (مورد انتظار، اجرا نشده). با migration اعمال‌شده روی اتصال read_model و listener ثبت‌شده:

bash
php artisan test --filter=OrderSummaryProjection
#   PASS  Tests\Feature\OrderSummaryProjectionTest
#   ✓ it converges whatever the arrival order
#   ✓ it ignores a duplicate delivery
#   ✓ it shows pending when only a downstream fact has arrived
#   ✓ it rebuilds to the same row
#   ✓ it matches the snapshot
php artisan order-summary:rebuild
#   replayed up to position 3
#   swapped
curl -i 'http://localhost/order-summaries/o-1?min_version=2'
#   HTTP/1.1 202 Accepted
#   Retry-After: 1
#   {"order_id":"o-1","status":"processing"}

۵. تأخیر را اندازه بگیرید. query تأخیر از سازوکار را اجرا کنید در حالی که worker صف را برای ۳۰ ثانیه متوقف کرده‌اید (php artisan queue:pause redis:projections): lag_by_event_time برای منبع‌های متوقف حدود ۳۰ ثانیه بالا می‌رود و بعد از php artisan queue:continue redis:projections پایین می‌آید.

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

باورواقعیت
«CQRS یعنی دو دیتابیس و یک broker.»Young: CQRS "is simply the creation of two objects where there was previously only one"؛ انبار و پیام‌رسانی قدم‌های بعدی و اختیاری‌اند.
«هر سرویس باید CQRS داشته باشد.»Fowler: فقط "specific portions of a system (a BoundedContext in DDD lingo)"؛ بیشتر contextها به CRUD می‌خورند.
«CQRS به event sourcing نیاز دارد.»OrderSummary ما aggregate با ذخیرهٔ وضعیت و outbox دارد؛ event sourcing انتخاب جدای سمت نوشتن است.
«Database per service یعنی یک سرور برای هر سرویس.»Richardson جدول خصوصی یا schema برای هر سرویس روی سرور مشترک را کم‌سربارترین گزینه‌ها می‌شمارد.
«خواندن جدول سرویس دیگر بی‌ضرر است.»خواندن schema و بار را به هم می‌دوزد؛ تغییر نام خواننده را می‌شکند، query طولانی به صاحب آسیب می‌زند.
«read replica یعنی CQRS داریم.»همان schema، همان صاحب، به‌اضافهٔ تأخیر؛ خواندن را مقیاس می‌دهد، مدل‌ها را جدا نمی‌کند.
«read model همان cache است.»شکل دیگری است، با event پر می‌شود، مال خواننده است، قابل بازسازی است و هرگز read-through نیست.
«تحویل دقیقاً یک‌بار dedup را بی‌نیاز می‌کند.»brokerها و Debezium هنگام خرابی حداقل یک‌بار تحویل می‌دهند؛ کلید dedup در همان تراکنش اثر را یک‌بار می‌کند.
«فرمان باید void برگرداند، پس نمی‌توانیم چیزی به کلاینت بگوییم.»برگرداندن توکن نسخه خواندن را در سمت خواندن نگه می‌دارد و read-your-writes را ممکن می‌کند.
«projector را سریع کنیم، کاربر نوشته‌اش را می‌بیند.»تأخیر از میلی‌ثانیه تا دقیقه تغییر می‌کند؛ read-your-writes توکن، چسبندگی یا خوش‌بینی UI می‌خواهد.
«از دیتابیس سرویس‌های دیگر بازسازی کنیم.»مال شما نیست که بخوانید؛ log خودتان از eventهای دریافتی یا retention‌ای را که کنترلش با شماست نگه دارید.
«materialized view یک read model میان‌سرویسی است.»همهٔ جدول‌ها را در یک دیتابیس می‌خواهد، پس فقط درون یک صاحب یا یک modular monolith کار می‌کند.
«BI می‌تواند از replicaها query بگیرد.»replicaها schema درونی دارند و تعارض replay می‌سازند؛ جای گزارش warehouse است.

چکیده (Cheat sheet) ​

موضوعبه یاد داشته باشید
مسئلهٔ دادهjoin میان سرویس‌ها نداریم (compose یا project)، تراکنش میان سرویس‌ها نداریم (saga + outbox)
دیتابیس مشترکبرای نوشتن ممنوع؛ فقط به‌شکل view منتشرشده توسط صاحب یا جدول قراردادی فقط-درج در دوران مهاجرت تحمل می‌شود
دیتابیس برای هر سرویسدادهٔ خصوصی؛ جدول، schema یا سرور؛ schema + role پیش‌فرض رایج است
Polyglot persistenceهر سرویس و هر read model انباری را برمی‌دارد که به پرس‌وجوهایش می‌خورد
CQSفرمان تغییر می‌دهد و داده برنمی‌گرداند؛ پرس‌وجو داده برمی‌گرداند و چیزی را تغییر نمی‌دهد
CQRSاول دو شیء؛ بعد جدول خواندنی؛ بعد انبار خواندنی؛ هرچه زودتر توقف کنید
projection هم‌زمان در برابر ناهم‌زمانهمان تراکنش = بدون تأخیر، همان دیتابیس؛ event = تأخیر، هر انباری
Read modelبرای هر صفحه، denormalised، مال خواننده، قابل بازسازی، نسخه‌دار
Projectordedup با event id + upsert ستون‌های خودی + version guard، در یک تراکنش؛ ack بعد از commit
eventهای نامرتبupsert، هرگز «اگر بود به‌روز کن»؛ وضعیت را از واقعیت‌های موجود استخراج کنید
بازسازیreceived_events خودتان را تا یک حصار در جدول تازه بازپخش کنید، جبران کنید، کوتاه قفل کنید، جایگزین کنید
گزینه‌های رساندن دادهreplica (مقیاس)، logical replication (جدول‌های انتخابی)، CDC (log → event)، event (قرارداد)، matview (یک دیتابیس)
Read-your-writesتوکن نسخه + صبر، خواندن چسبنده، خوش‌بینی UI، یا projection هم‌زمان
خرابی‌های سازگاری نهاییفهرست کهنه، حذف شبح‌وار، رستاخیز، والد گم‌شده: سنگ‌قبر + version guard + هشدار
گزارش‌گیریwarehouse با CDC/event؛ هرگز سرویس‌های production
پایشprojection_lag_seconds برای هر منبع، سطرهای pending، اندازهٔ DLQ، WAL نگه‌داشته

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

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

۱ — دو توانایی‌ای را نام ببرید که یک دیتابیس واحد می‌دهد و با database per service از دست می‌رود، و الگویی که جای هرکدام را می‌گیرد. حیاتی ​

پاسخ

پاسخ: join میان صاحبان (جایش API composition یا read model در CQRS) و تراکنش اتمی میان صاحبان (جایش sagaیی از تراکنش‌های محلی، با outbox برای انتشار مطمئن).

۲ — Billing فقط sales.orders را می‌خواند. چرا این هنوز مسئلهٔ دیتابیس مشترک است؟ حیاتی ​

پاسخ

پاسخ: وابستگی در زمان توسعه (Sales نمی‌تواند جدول را بی‌شکستن Billing تغییر نام یا شکل دهد) و وابستگی در زمان اجرا (queryهای Billing روی دیتابیس Sales قفل، snapshot و I/O می‌گیرند). راه‌حل یک قرارداد است: API، event، یا view یا جدولی که صاحب منتشر می‌کند.

۳ — Richardson کدام سه درجه را برای خصوصی نگه داشتن داده می‌شمارد و کدام دو ارزان‌ترند؟ تکمیلی ​

پاسخ

پاسخ: جدول خصوصی برای هر سرویس، schema برای هر سرویس، سرور دیتابیس برای هر سرویس؛ دوتای اول "have the lowest overhead".

۴ — آیا func (h Handler) Handle(cmd PlaceOrder) (Ack, error) با Ack{OrderID, Version} CQS را می‌شکند؟ مهم ​

پاسخ

پاسخ: به‌طور سخت‌گیرانه مقداری برمی‌گرداند؛ عمل‌گرایانه هیچ دادهٔ خواندنی برنمی‌گرداند، فقط شناسه‌ای که کلاینت از قبل می‌داند و یک توکن نسخه. همهٔ خواندن‌ها را در سمت پرس‌وجو نگه می‌دارد و read-your-writes را ممکن می‌کند، و برای همین انحرافی رایج و پذیرفته است.

۵ — به گفتهٔ Young خود CQRS چیست و چه نیست؟ حیاتی ​

پاسخ

پاسخ: "simply the creation of two objects where there was previously only one"، با جداسازی بر اساس فرمان یا پرس‌وجو. سازگاری نهایی، eventing، پیام‌رسانی، انبارهای جدا یا event sourcing نیست؛ این‌ها تصمیم‌هایی دور آن‌اند.

۶ — Fowler می‌گوید CQRS کِی نمی‌ارزد و برای پرس‌وجوهای سنگین چه پیشنهاد می‌کند؟ مهم ​

پاسخ

پاسخ: وقتی domain به مدل CRUD می‌خورد یا هم‌پوشانی کافی میان سمت فرمان و پرس‌وجو هست؛ "risky complexity" اضافه می‌کند. برای چند پرس‌وجوی سنگین ReportingDatabase را پیشنهاد می‌کند در حالی که سیستم اصلی بیشتر پرس‌وجوها را جواب می‌دهد.

۷ — ParcelDispatched پیش از OrderPlaced می‌رسد. کدام دو انتخاب طراحی projector را درست نگه می‌دارند؟ مهم ​

پاسخ

پاسخ: upsert (اگر سطر نیست بسازش) و نوشتن فقط ستون‌هایی که مال context آن event است؛ و استخراج وضعیت از واقعیت‌های موجود (سطری بدون placed_at یعنی «pending»). ستون‌های Sales را با version از Sales محافظت کنید تا جابه‌جایی درون Sales هم پوشش داده شود.

۸ — چرا insert مربوط به dedup و به‌روزرسانی سطر خواندنی باید در یک تراکنش باشند، و کِی ack می‌کنید؟ حیاتی ​

پاسخ

پاسخ: تا «دیده‌شده» و «اعمال‌شده» بعد از crash هرگز با هم اختلاف نداشته باشند؛ و ack بعد از commit می‌آید، پس crash پیش از ack فقط تحویل دوباره می‌سازد که کلید dedup آن را بی‌اثر می‌کند.

۹ — چرا سمت خواندن received_events را نگه می‌دارد به‌جای اینکه از دیتابیس Fulfilment و Billing بازسازی کند؟ مهم ​

پاسخ

پاسخ: آن دیتابیس‌ها خصوصی صاحبانشان‌اند؛ خواندنشان دیتابیس مشترک را برمی‌گرداند. log فقط-افزودنی خود سمت خواندن (یا retention‌ای در broker که کنترلش با خودش است) منبع بازپخش است.

۱۰ — کاربری سفارش می‌دهد و فهرست آن را نشان نمی‌دهد. چهار راهبرد و راهبرد پیش‌فرضتان را بگویید. حیاتی ​

پاسخ

پاسخ: توکن نسخه + صبر برای projection (پیش‌فرض برای read model ناهم‌زمان)، خواندن چسبنده از سمت نوشتن، خوش‌بینی UI، projection هم‌زمان در همان تراکنش.

۱۱ — کدام گزینهٔ رساندن داده هم مالکیت را رعایت می‌کند و هم اجازهٔ تغییر آزادانهٔ شکل نسخه را می‌دهد؟ تکمیلی ​

پاسخ

پاسخ: projection مبتنی بر event (eventها قرارداد طراحی‌شده‌اند و projector می‌تواند هر شکلی بسازد). CDC و logical replication فقط وقتی مالکیت را رعایت می‌کنند که صاحب جدول قراردادی منتشر کند، و logical replication فقط می‌تواند ستون و سطر انتخاب کند.

۱۲ — محصولی که در سمت نوشتن حذف شده یک ساعت بعد دوباره در جست‌وجو پیدا می‌شود. علت و راه‌حل را بگویید. مهم ​

پاسخ

پاسخ: رستاخیز: یک event به‌روزرسانی قدیمی‌تر بعد از حذف اعمال شده. یک سنگ‌قبر با version نگه دارید و eventها را فقط وقتی version تازه‌تری دارند اعمال کنید (یا از external versioning در موتور جست‌وجو استفاده کنید).

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

اصطلاحمعنا
commit دومرحله‌ای (2PC)commit اتمی میان چند منبع؛ میان سرویس‌ها از آن پرهیز می‌شود
API compositionاز صاحبان بپرس و نتیجه‌ها را در حافظه join کن
تحویل حداقل‌یک‌بار (At-least-once delivery)پیام ممکن است بیش از یک بار برسد، هرگز گم نمی‌شود
Bounded contextمرزی که یک مدل درونش معتبر است؛ CQRS برای هر context جدا تصمیم‌گیری می‌شود
جبران عقب‌ماندگی (Catch-up)پردازش کارهای عقب‌افتاده از آخرین موقعیت پیش از گرفتن ترافیک زنده
CDC (Change data capture)تبدیل log دیتابیس به جریانی از eventهای تغییر سطر
فرمان (Command)درخواست تغییر وضعیت با فعل امری؛ ممکن است رد شود
توکن سازگاری / توکن نسخه (Version token)version aggregate که فرمان برمی‌گرداند و کلاینت برای خواندن نوشتهٔ خودش به کار می‌برد
CQRSCommand Query Responsibility Segregation: شیء/مدل/انبار جدا برای نوشتن و خواندن
CQSCommand-Query Separation: متد یا وضعیت را عوض می‌کند یا داده برمی‌گرداند
دیتابیس برای هر سرویس (Database per service)دادهٔ هر سرویس خصوصی است و فقط از API یا eventهایش در دسترس است
Debeziumپلتفرم متن‌باز CDC روی Kafka Connect
Denormalisedدادهٔ تکراری برای پرهیز از join هنگام خواندن
Event sourcingذخیرهٔ aggregate به‌شکل دنبالهٔ eventهایش
سازگاری نهایی (Eventual consistency)اگر به‌روزرسانی تازه‌ای نیاید نسخه‌ها هم‌گرا می‌شوند؛ در این فاصله خواندن ممکن است عقب باشد
به‌روزرسانی idempotentاعمال دوبارهٔ یک event همان اثر یک‌بار را دارد
Logical replicationreplication تغییرات داده در PostgreSQL بر اساس replica identity، از راه publication و subscription
Materialized viewنتیجهٔ ذخیره‌شدهٔ یک query که صریحاً تازه می‌شود
Outboxجدولی که در همان تراکنش aggregate نوشته و به broker رله می‌شود
حذف شبح‌وار (Phantom delete)آیتم حذف‌شده‌ای که هنوز در read model دیده می‌شود
ماندگاری چندزبانه (Polyglot persistence)استفاده از فناوری‌های ذخیره‌سازی متفاوت برای نیازهای متفاوت
Projectionتابعی از eventها به سطرهای read model
تأخیر projection (Projection lag)read model چقدر از eventهایی که آن را ساخته‌اند عقب است
Projector (projection handler)کدی که eventها را روی read model اعمال می‌کند
Publication / subscriptionاشیای PostgreSQL که تعیین می‌کنند چه چیزی replicate شود و چه کسی دریافت کند
Read modelنسخه‌ای به شکل پرس‌وجو که مال خواننده است
Read replicaنسخهٔ فیزیکی دیتابیس برای خواندن، با تأخیر replication
Read-your-writesضمانت session که کلاینت نوشته‌های قبلی خودش را می‌بیند
بازسازی (Rebuild)ساختن دوبارهٔ read model با بازپخش log مربوط به eventهایش
Replay fixtureدنبالهٔ ضبط‌شدهٔ eventها که به‌عنوان ورودی تست استفاده می‌شود
Replica identityستون‌هایی که PostgreSQL برای شناسایی سطر در logical replication مربوط به update و delete به کار می‌برد
دیتابیس گزارش (Reporting database)دیتابیس جدا با شکل مناسب گزارش (Fowler)
رستاخیز (Resurrection)event قدیمی که سطر حذف‌شده را دوباره می‌سازد
Sagaدنباله‌ای از تراکنش‌های محلی با جبران‌کننده
دیتابیس مشترک (Shared database)چند سرویس که به جدول‌های یکسان دسترسی دارند
Snapshot test (golden file)مقایسهٔ خروجی با فایل مورد انتظار commitشده
خواندن چسبنده (Sticky reads)خواندن از سمت نوشتن برای مدتی بعد از نوشتن (sticky در Laravel)
UI مبتنی بر وظیفه (Task-based UI)UIای که فرمان‌های با نام نیت می‌فرستد نه کل رکورد را
لایهٔ خواندن نازک (Thin read layer)سمت پرس‌وجوی Young: SQL مستقیم به DTO، با دور زدن مدل domain
سنگ‌قبر (Tombstone)سطر نشانه‌ای که حذف و version آن را ثبت می‌کند
خوش‌بینی UI (UI optimism)نشان دادن نتیجهٔ مورد انتظار پیش از تأیید سرور
Version guardاعمال به‌روزرسانی فقط اگر version آن از version ذخیره‌شده تازه‌تر باشد
انبار داده (Warehouse)انبار تحلیلی که از سیستم‌های عملیاتی پر می‌شود
مدل نوشتن (Write model)مدلی که فرمان‌ها را پردازش و از invariantها محافظت می‌کند (aggregateها)

منابع (References) ​

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