Skip to content

Service Boundaries: Teams, Conway's Law, the Distributed Monolith and the Hidden Tax ​

"Any organization that designs a system (defined more broadly here than just information systems) will inevitably produce a design whose structure is a copy of the organization's communication structure." — Melvin E. Conway، یادداشت نویسنده بر How Do Committees Invent? (Datamation، آوریل ۱۹۶۸)

خلاصه (Summary): مرز سرویس (Service boundary) خطی است که هم‌زمان دور داده، رفتار، یک تیم و یک واحد استقرار کشیده می‌شود؛ آن را جایی بکشید که تغییر و گفت‌وگو به‌طور طبیعی کم است، وگرنه هر قابلیت یک مالیات پنهان (Hidden tax) از جنس هماهنگی، تأخیر و قطعی می‌پردازد. تمرکز (Focus): مرز دقیقاً چیست، قانون Conway و مانور معکوس Conway، Team Topologies و بار شناختی، شش راهبرد تجزیه، آزمون‌های مرز، انواع coupling از نگاه Newman، distributed monolith، مالیات پنهان میکروسرویس، integratorها و disintegratorهای دانه‌بندی، context mapping میان سرویس‌ها، تکامل مرز (ادغام، شکستن، strangler fig، tactical forking) و سنجش سلامت مرز از روی deployها، call graph و تاریخچهٔ git. هدف یادگیری (Learning goal): با داشتن یک سیستم و یک چارت سازمانی، مرز سرویس پیشنهاد بدهید، coupling باقی‌مانده و هزینه‌اش را نام ببرید، distributed monolith را با عدد (نه با نظر) تشخیص بدهید، و مرزهایی را که انتخاب کرده‌اید با تست معماری، contract test و گزارش change coupling در Go و Laravel پاسبانی کنید.

این فصل در گروه AR 03 (میکروسرویس در عمل) است. فرض می‌کند می‌دانید چرا اصلاً کسی سرویس انتخاب می‌کند (Monolith در برابر Microservices و Modular Monolith، معماری Microservices) و مرز ماژول درون یک deployable چه شکلی است (Modular Monolith). پرسشی که این صفحه صاحبش است: خط‌ها کجا بروند و هر خط چه هزینه‌ای دارد؟ بقیه را همسایه‌ها می‌گویند: سرویس‌ها چطور حرف می‌زنند (ارتباط سرویس‌ها)، چه کسی صاحب کدام جدول است (مالکیت داده در Microservices)، لبهٔ سیستم (API Gateway، BFF و Service Mesh)، و مدل‌سازی DDD پشت یک context (Bounded Context، Context Map).

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

دنبال چه هستیدبروید به
کل صفحه در چهار جدولهمه‌چیز در یک دقیقه
چرا خط مهم‌تر از فناوری استچرا مرز وجود دارد
از Conway 1968 تا Team Topologies و Hard Partsاز کجا آمده
داده + رفتار + تیم + استقرارمرز چیست
قانون Conway، مانور معکوسقانون Conway، Inverse Conway
stream-aligned، platform، enabling، complicated-subsystemTeam Topologies
بر اساس capability، subdomain، volatility، داده، مقیاس، complianceراهبردهای تجزیه
information hiding، با هم تغییر کردن، تراکنش، آزمون پرحرفیآزمون‌های مرز
coupling دامنه، زمانی، استقرار، پیاده‌سازیانواع coupling
deploy هم‌قدم، DB مشترک، زنجیرهٔ sync، کتابخانهٔ مشترکDistributed monolith
تأخیر، سازگاری، دیباگ، تست، on-callمالیات پنهان
چقدر بزرگ، nanoserviceدانه‌بندی
partnership، shared kernel، ACL، OHS، conformistContext mapping میان سرویس‌ها
ادغام، شکستن، strangler fig، tactical forkingتکامل مرز
coupling استقرار، call graph، change coupling از gitسنجش سلامت مرز
Orders و Billing درست و غلط، با تستGo، Laravel
DB مشترک، زنجیرهٔ sync، سرویس‌های entity، هم‌قدمیحل مسئله‌های کلاسیک
کدام راهبرد برای کدام وضعیتانتخاب
از monolith تا دادهٔ توزیع‌شدهدر معماری
تمرین عملیآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

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

واژهبه زبان سادهمثال کوچکبدون آن چه می‌شود
مرز سرویس (Service boundary)خطی دور داده، کد، تیم و انتشار یک سرویسBilling صاحب invoices، کدش، pagerش و pipelineش استدو تیم یک جدول را ویرایش می‌کنند و همدیگر را مقصر می‌دانند
قانون Conway (Conway's law)سیستم از ساختار ارتباطی سازندگانش کپی می‌شودسه تیم لایه‌ای، سه لایه می‌سازندمعماری با چارت سازمانی می‌جنگد و می‌بازد
مانور معکوس Conway (Inverse Conway manoeuvre)اول تیم‌ها را عوض کن تا معماری دلخواه بیایدتیم Orders را پیش از جدا کردن orders بسازسرویس‌هایی می‌کشید که هیچ‌کس نمی‌تواند صاحبشان باشد
بار شناختی (Cognitive load)چقدر یک تیم باید در ذهن نگه داردیک تیم صاحب ۱۴ سرویس و ۳ دیتابیستغییرهای کند، قطعی‌هایی که کسی نمی‌فهمد
Bounded contextمحدوده‌ای که یک مدل و یک واژگان در آن معتبر است«مشتری» در Billing حساب است، در Support یک آدمیک مدل غول‌آسا با معناهای متناقض
وابستگی (Coupling)چقدر تغییر در یک جا تغییر جای دیگر را لازم می‌کندتغییر نام یک ستون سرویس دیگری را می‌شکندهر انتشار یک جلسه لازم دارد
Distributed monolithسرویس‌هایی که هنوز باید با هم تغییر کنند، deploy شوند و خراب شوندپنج سرویس، یک release train، یک دیتابیسهزینهٔ میکروسرویس را می‌دهید و monolith تحویل می‌گیرید
مالیات پنهان (Hidden tax)هزینه‌هایی که با شبکه می‌آیند نه با قابلیت‌هاretry، tracing، contract test، on-callسرعت تیم بعد از جداسازی می‌افتد

Coupling و مالیاتش (چهار نوع Newman؛ جزئیات در انواع coupling):

Couplingبه زبان سادهمنبع رایجمالیاتی که می‌دهیددرمان
دامنه (Domain)A به کاری که B می‌کند نیاز داردBilling باید بداند سفارشی ثبت شدکم، اگر قرارداد کوچک باشدpublished language باریک
زمانی (Temporal)A فقط وقتی کار می‌کند که B بالا باشدزنجیرهٔ فراخوانی هم‌زماندسترس‌پذیری ضرب می‌شود، تأخیر جمعevent، کپی محلی، timeout
استقرار (Deployment)A و B باید با هم منتشر شوندrelease train، نسخه‌های هم‌قدمهمهٔ تیم‌ها منتظر کندترین می‌مانندقراردادهای سازگار با عقب
پیاده‌سازی (Implementation)A به درونیات B وابسته استجدول مشترک، کتابخانهٔ دامنهٔ مشترکB دیگر نمی‌تواند تنها تغییر کنددرونیات را پنهان کن؛ فقط API یا event

راهبردهای تجزیه (مقایسه در راهبردهای تجزیه):

راهبردامتداد برشانتخاب اول خوب وقتیمراقب باشید
Business capabilityکاری که کسب‌وکار می‌کند (Orders، Billing)سازمان از قبل صاحب capability داردcapabilityهایی که یک invariant مشترک دارند
Subdomain / bounded contextجایی که زبان و مدل عوض می‌شوددامنه غنی است، کارشناس‌ها سر واژه‌ها اختلاف دارندcontextهای خیلی ریز، سرویس‌های زیاد
Volatilityچیزی که زیاد تغییر می‌کند در برابر پایداریک بخش هر هفته عوض می‌شود، بقیه ثابتتغییرپذیری موقت
مالکیت داده (Data ownership)نویسندهٔ یکتای هر رکورد کیستامروز چند نویسنده روی یک جدولگزارش‌هایی که همه‌چیز را join می‌کنند
نیاز مقیاس (Scaling needs)الگوی بار بسیار متفاوتجست‌وجو ۹۵٪ ترافیک را می‌گیردشکستن برای مقیاسی که ندارید
Compliance / امنیتدادهٔ تنظیم‌شده و شعاع انفجاردادهٔ کارت (PCI DSS)، دادهٔ سلامتدادهٔ تنظیم‌شده باز هم پخش می‌شود

Distributed monolith: نشانه → آزمون → درمان.

نشانهآزمون سریعدرمان
deploy هم‌قدم (Lockstep)سهم انتشارهایی که انتشار سرویس دیگری را هم لازم داشتندقرارداد expand/contract، event نسخه‌دار
دیتابیس مشترکبیش از یک role سرویس روی یک جدول حق نوشتن دارددیتابیس برای هر سرویس، یا schema + role برای هر سرویس
زنجیرهٔ فراخوانی هم‌زمانعمق call graph برای یک درخواست کاربرevent، تکثیر داده، ادغام جفت پرحرف
کتابخانهٔ مشترک با منطق دامنهیک کلاس دامنه در ۲ سرویس یا بیشتر import شدهکپی، انتشار قرارداد، یا ادغام
Change couplingدو سرویس در بیش از ۳۰٪ commitها با همجابه‌جایی مرز یا ادغام

چرا مرز وجود دارد ​

هر سیستمی که از اندازه‌ای بزرگ‌تر شود جایی شکسته می‌شود، چون هیچ آدمی کلش را در ذهن ندارد و هیچ تیمی به‌تنهایی به‌اندازهٔ کافی سریع عوضش نمی‌کند. پس سؤال هیچ‌وقت این نیست که آیا مرز داریم؛ سؤال این است که مرزها کجا هستند و چه چیزی از آن‌ها رد می‌شود. مرز خوب بیشتر تغییرها را یک طرف نگه می‌دارد؛ مرز بد هر قابلیت را به پروژه‌ای میان‌تیمی تبدیل می‌کند. در monolith، مرز ماژول بد کمی refactoring خرج دارد. روی شبکه، همان اشتباه تأخیر، خرابی جزئی، یک قرارداد برای نسخه‌گذاری و یک نوبت‌کشیک خرج دارد؛ برای هر درخواست، برای همیشه. برای همین مقالهٔ Microservices فاولر می‌گوید بخش سخت خود سرویس‌ها نیست: "It's hard to figure out exactly where the component boundaries should lie."

مرز در امتداد خط تیم و تغییرمرز در امتداد خط فنی (لایه، entity)
بیشتر قابلیت‌ها یک سرویس را لمس می‌کنندبیشتر قابلیت‌ها همهٔ سرویس‌ها را لمس می‌کنند
تیم‌ها تنها deploy می‌کنندrelease train و هیئت تأیید تغییر
خرابی محلی می‌ماندیک سرویس کند بقیه را پایین می‌کشد
بخشی از داده عمداً تکرار می‌شودداده یک جاست و همه آن را می‌خوانند
اول کار سخت‌تر: باید کسب‌وکار را بفهمیداول کار آسان: نمودار دیتابیس همان نقشه است
مناسب: محصول بلندعمر با چند تیممناسب: هیچ‌چیز در سطح سرویس؛ به‌عنوان لایه درون یک سرویس خوب است

تمثیلی که در این صفحه بارها برمی‌گردد: آشپزخانهٔ رستوران. آشپزخانه ایستگاه دارد: کباب، پیش‌غذای سرد، شیرینی. هر ایستگاه مواد خودش، ابزار خودش و آشپز خودش را دارد و بشقاب آماده را به پیشخوان تحویل می‌دهد. اگر شیرینی‌پز برای هر دسر باید برود از ایستگاه کباب تابه قرض بگیرد (کتابخانهٔ مشترک)، اگر همهٔ ایستگاه‌ها یک برگهٔ سفارش را بخوانند و رویش خط بزنند (دیتابیس مشترک)، یا اگر کباب تا شیرینی دسر را تأیید نکند نتواند استیک را بچیند (زنجیرهٔ هم‌زمان)، شما یک آشپزخانه دارید که ادای سه تا را درمی‌آورد. ایستگاه‌ها مرزند؛ پیشخوان و برگهٔ سفارش قرارداد؛ و نقشهٔ چیدمان آشپزها از طرف سرآشپز همان قانون Conway است.

Teams split by layerStream-aligned teams + platformUI teamBackend teamDBA teamweb/ layerservices/ layerone shared schemaproducesSystem: three layersUIAPIDBfeature Afeature Bfeature COrders teamstream-alignedBilling teamstream-alignedCatalog teamstream-alignedPlatform team: CI, broker, observability (X-as-a-Service)producesorders-svcown DBUI + API + databilling-svcown DBUI + API + datacatalog-svcown DBUI + API + dataevents + published APIs between servicesinverseConway

تصویر قانون را در دو جهت نشان می‌دهد: تیم‌هایی که بر اساس لایه تقسیم شده‌اند سیستمی لایه‌ای می‌سازند که در آن هر قابلیت از سه تیم می‌گذرد؛ تیم‌های stream-aligned همراه یک تیم platform سرویس‌هایی می‌سازند که آینهٔ خودشان است.

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

  1. «مرز یک تصمیم فنی است.» اول یک تصمیم اجتماعی و اقتصادی است. نتیجه‌گیری مقالهٔ Conway این است که "a design effort should be organized according to the need for communication"؛ خطی که می‌کشید تعیین می‌کند چه کسی باید با چه کسی حرف بزند.
  2. «سرویس کوچک‌تر یعنی جداتر.» اندازه و coupling دو محور جدا هستند. ده سرویس ریز که همیشه با هم تغییر می‌کنند از یک سرویس خوش‌مرز وابسته‌ترند. Hard Parts هشدار می‌دهد: "One common mistake many development teams make is focusing too much on granularity disintegrators while ignoring granularity integrators."
  3. «اگر repository و container جدا داریم، میکروسرویس داریم.» پردازه‌های جدا با دیتابیس مشترک، کتابخانهٔ دامنهٔ مشترک و یک release train یعنی distributed monolith: هزینهٔ توزیع بدون سودش.

از کجا آمده ​

Conway، ۱۹۶۸. مقالهٔ How Do Committees Invent? از Melvin Conway در آوریل ۱۹۶۸ در Datamation منتشر شد. استدلالش از جنس نظریهٔ گراف است: ساختار سازمان طراحی و ساختار سیستم با یک همریختی (Homomorphism) به هم مربوط‌اند، رابطه‌ای "so simple that in some cases it is an identity". او توضیح می‌دهد چرا سازمان بزرگ بدتر می‌شود نه بهتر: "the number of possible communication paths in an organization is approximately half the square of the number of people"؛ پس ارتباط باید محدود شود، و سیستم همان محدودیت‌ها را به ارث می‌برد.

Brooks، ۱۹۷۵. Fred Brooks در The Mythical Man-Month اسمش را «قانون Conway» گذاشت (این را از پانویس bliki فاولر داریم، نه از خود کتاب).

Parnas، ۱۹۷۲. On the Criteria To Be Used in Decomposing Systems into Modules قاعده‌ای داد که این فصل برای سرویس‌ها هم به کار می‌برد: بر اساس تصمیم‌های طراحی که احتمالاً تغییر می‌کنند بشکن و هر کدام را پشت یک interface پنهان کن (ببینید کیفیت طراحی).

Evans، ۲۰۰۳. Domain-Driven Design مفهوم bounded context و context map را آورد. DDD Reference رایگان Evans (۲۰۱۵) bounded context را این‌طور تعریف می‌کند: "A description of a boundary (typically a subsystem, or the work of a particular team) within which a particular model is defined and applicable." به «the work of a particular team» دقت کنید: DDD از همان اول مرز مدل را به تیم گره زد.

LeRoy و Simons، ۲۰۱۰. فاولر اصطلاح «inverse Conway maneuver» را به Jonny LeRoy و Matt Simons در شمارهٔ دسامبر ۲۰۱۰ Cutter IT Journal نسبت می‌دهد (پانویس فاولر را خواندیم، نه خود مقاله را).

Lewis و Fowler، ۲۰۱۴. مقالهٔ Microservices (مارس ۲۰۱۴) مرز را مرکز این سبک کرد: سرویس‌ها "organized around business capabilities"، با "Decentralized Data Management"، و این قاعده: "If you find yourself repeatedly changing two services together, that's a sign that they should be merged."

Newman، ۲۰۱۵ و ۲۰۱۹. Building Microservices (ویراست اول، فوریهٔ ۲۰۱۵) ایدهٔ درز (Seam) از Feathers را برای پیدا کردن مرز سرویس در monolith به کار برد: "bounded contexts make excellent seams". Monolith to Microservices (۲۰۱۹) بخشی به نام «On Coupling And Cohesion» و الگوهای مهاجرت (strangler fig، branch by abstraction، parallel run) دارد. چهار نوع coupling که این‌جا به کار می‌بریم از فصل اول همین کتاب است؛ طرح فصل را در صفحهٔ کتاب روی سایت خود Newman تأیید کردیم و فهرست انواع را از یادداشت‌های یک خواننده (منبع ثانویه).

Monolith First، ۲۰۱۵. MicroservicePremium (۱۳ مه ۲۰۱۵) و MonolithFirst (۳ ژوئن ۲۰۱۵) از فاولر استدلال کردند که میکروسرویس‌ها "only work well if you come up with good, stable boundaries between the services"، و این مرزها را درون یک monolith بهتر یاد می‌گیرید.

Team Topologies، ۲۰۱۹. Matthew Skelton و Manuel Pais چهار نوع تیم و سه حالت تعامل را شرح دادند و بار شناختی را حد آن چیزی دانستند که یک تیم (و در نتیجه مجموعه‌ای از سرویس‌ها) می‌تواند صاحبش باشد. خلاصهٔ فاولر (۲۵ ژوئیهٔ ۲۰۲۳) تمرکز بر بار شناختی را "the bright insight of Team Topologies" می‌نامد.

Hard Parts، ۲۰۲۱. Software Architecture: The Hard Parts از Ford، Richards، Sadalage و Dehghani (ویراست اول، اکتبر ۲۰۲۱) disintegratorها و integratorهای دانه‌بندی را داد و دو رویکرد تجزیه برای سیستم موجود: component-based decomposition و tactical forking.

text
     Year   Idea                                       What it changed for boundaries
1    1968   Conway: system copies communication        Org design is architecture design
2    1972   Parnas: hide decisions likely to change     Boundaries follow change, not steps
3    2003   Evans: bounded context, context map         One model per boundary; relations named
4    2010   Inverse Conway manoeuvre                    Change teams to get the architecture
5    2014   Microservices: business capabilities        Boundary = team = deployable = data
6    2015   Newman: seams; Fowler: Monolith First        Find boundaries before distributing them
7    2019   Team Topologies: cognitive load             Team capacity limits service ownership
8    2021   Hard Parts: integrators/disintegrators      Granularity as a measured trade-off

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

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

مرز چیست حیاتی ​

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

بدفهمی رایج: «مرز یعنی repository یا container جدا.» این‌ها بسته‌بندی‌اند. مرز چهار وجه دارد و اگر هر کدام مشترک باشد، مرز نشت می‌کند.

تعریف: مرز سرویس چهار چیز را هم‌راستا می‌کند: داده (یک سرویس منبع حقیقت و تنها نویسنده است)، رفتار (قاعده‌هایی که داده را معتبر نگه می‌دارند کنار همان داده‌اند)، تیم (یک تیم بدون اجازه گرفتن هر دو را عوض می‌کند)، و استقرار (می‌شود تنها منتشرش کرد). Lewis و Fowler مؤلفه را "a unit of software that is independently replaceable and upgradeable" تعریف می‌کنند؛ این چهار وجه همان چیزی است که این تعریف را برای یک سرویس درست می‌کند.

text
     Change request: "invoices get a due date per customer segment"
1    Billing team edits billing.invoices + rule code          data + behaviour inside one boundary
2    Billing contract unchanged (new optional field only)      no other team involved
3    Billing deploys at 14:05                                   deployment alone
4    Orders, Shipping keep running v1 consumers                 nobody else redeploys
     Leaky version: Orders also writes billing.invoices -> step 2 needs the Orders team, step 3 waits for theirs

سناریوی واقعی: فروشگاهی که Orders در billing_invoices ردیف درج می‌کند «چون سریع‌تر است»؛ Billing دیگر نمی‌تواند ستون NOT NULL اضافه کند بی‌آنکه Orders بشکند. بانکی که سرویس دفتر کل تنها نویسندهٔ موجودی‌هاست و بقیه یا می‌پرسند یا گوش می‌دهند. بیمه‌ای که یک تیم صاحب سه سرویس است که همیشه با هم deploy می‌شوند: این یک مرز است در سه container.

چهار وجه، و آنچه هر کدام را می‌شکند:

وجهسالمنشتتشخیص با
داده (Data)یک نویسنده برای هر جدول؛ بقیه از API/event می‌خوانندسرویس دوم جدول را می‌نویسد یا join می‌کندroleها و grantهای DB؛ لاگ کوئری
رفتار (Behaviour)قاعده کنار داده‌ای است که از آن محافظت می‌کندهمان قاعده در دو سرویس کپی شده یا در کتابخانهٔ مشترک استجست‌وجوی کد؛ change coupling
تیم (Team)یک تیم، on-call روشن«مالکیت مشترک»، دو تیم PR را تأیید می‌کنندCODEOWNERS، نوبت pager
استقرار (Deployment)pipeline و نسخهٔ مستقلrelease train، نسخه‌های هم‌قدملاگ deploy: چند بار انتشارها با هم رفته‌اند

راه درست: چهار وجه را برای هر سرویس بنویسید (یک جدول مالکیت در repo)، بعد داده را با roleهای دیتابیس، رفتار و وابستگی‌ها را با تست معماری، تیم را با CODEOWNERS و استقرار را با contract testهایی که اجازه می‌دهند هر pipeline تنها اجرا شود اعمال کنید.

قانون Conway حیاتی ​

به زبان ساده: سیستم آخرش شکل گفت‌وگوهای آدم‌هایی را می‌گیرد که می‌سازندش.

بدفهمی رایج: «قانون Conway دربارهٔ چارت سازمانی است.» دربارهٔ ارتباط است. خلاصهٔ فاولر از Chris Ford نقل می‌کند: "Conway understood that software coupling is enabled and encouraged by human communication." دو تیم زیر یک شاخهٔ چارت که هیچ‌وقت با هم حرف نمی‌زنند باز درز سختی می‌سازند؛ دو تیم در دو دپارتمان که هر روز با هم pair می‌کنند کد وابسته می‌سازند.

تعریف: Conway (۱۹۶۸): "organizations which design systems (in the broad sense used here) are constrained to produce designs which are copies of the communication structures of these organizations." فاولر (۲۰۲۲) دربارهٔ وزنش: "if there is one thing they all agree on, it's the importance and power of Conway's Law."

text
     Org: front-end team, back-end team, DBA team (activity-oriented)
1    Feature "gift wrapping" needs a UI field, an API field, a column
2    Front-end files a ticket for back-end; back-end files one for DBA
3    DBA adds the column in the next schema window (two weeks)
4    Back-end, tired of waiting, stores the flag in an existing JSON column
     Result: logic lands "in whichever application they have access to" (Lewis and Fowler) -> layers, not features

سناریوی واقعی: مثال کامپایلر فاولر: "if a single team writes a compiler, it will be a one-pass compiler, but if the team is divided into two, then it will be a two-pass compiler." معمار شش تیم در شش شهر: "There are going to be six major subsystems. I have no idea what they are going to be, but there are going to be six of them." شرکت remote-first که حالا منطقهٔ زمانی، نه دفتر، درزها را می‌کشد (فاولر می‌گوید منطقهٔ زمانی "still have a big effect, even online").

سازمان‌ها چطور واکنش نشان می‌دهند (سه واکنش فاولر):

واکنشیعنینتیجه
نادیده گرفتن (Ignore)معماری را بدون نگاه به تیم‌ها بکشیدسازمان می‌برد؛ مرزها فرسوده می‌شوند تا به تیم‌ها بخورند
پذیرفتن (Accept)مرز را جایی بکشید که ارتباط از قبل نازک استپایدار، شاید نه ایده‌آل
مانور معکوس Conwayتیم‌ها را عوض کنید تا مرز دلخواه بیایدوقتی کد و سازمان با هم عوض شوند جواب می‌دهد

راه درست: پیش از کشیدن مرز، گراف ارتباط را بکشید: چه کسی هر روز با چه کسی حرف می‌زند، چه کسی فقط با تیکت. مرز سرویس را روی یال‌های نازک بگذارید. گروه‌های کوچک ("A dozen or two people can have deep and informal communications") طبیعتاً monolith می‌سازند و این اشکالی ندارد.

مانور معکوس Conway مهم ​

به زبان ساده: اگر سیستم از تیم‌ها کپی می‌شود، تیم‌هایی را طراحی کنید که می‌خواهید سیستم از آن‌ها کپی شود.

بدفهمی رایج: «سازمان را عوض کن، معماری دنبالش می‌آید.» فاولر: "If you have an existing system with a rigid architecture that you want to change, changing the development organization isn't going to be an instant fix. Instead it's more likely to result in a mismatch between developers and code that adds friction."

تعریف: "we deliberately alter the development team's organization structure to encourage the desired software architecture" (فاولر، Conway's Law). قاعده‌ای که با آن جمع‌بندی می‌کند: "the modular decomposition of a system and the decomposition of the development organization must be done together."

text
     Goal: Billing as an independent service
1    Q1  Form a stream-aligned Billing team; it owns the billing module in the monolith
2    Q1  Team adds module boundary + arch test; only it approves billing/ changes (CODEOWNERS)
3    Q2  Billing schema + role; Orders reads via the module API
4    Q3  Billing extracted as a service behind the same API; events replace in-process calls
     Without step 1: an extracted service with no owner, patched by whoever is nearest

سناریوی واقعی: خرده‌فروشی که پیش از شکستن monolith تیم‌های «checkout» و «catalog» را می‌سازد؛ شرکت SaaS که دو نیم‌تیم را که مدام پای هم را لگد می‌کردند یکی می‌کند و بعد سرویس‌هایشان را هم ادغام می‌کند؛ تیم platform که ساخته می‌شود تا تیم‌های stream-aligned هر کدام اسکریپت deploy خودشان را ننویسند.

حرکتتغییر سازمانیتغییر کدی که باید همراهش باشد
ساختن تیم برای یک capabilityتیم stream-aligned تازهمرز ماژول یا سرویس، فایل مالکیت
ادغام دو تیمیک تیمادغام سرویس‌هایشان را بسنجید (تکامل)
ساختن تیم platformارائه‌دهندهٔ X-as-a-Servicepipeline سلف‌سرویس، قالب‌ها، broker
شکستن تیمی که بیش از حد بزرگ استدو تیماول درز را پیدا کنید؛ کد را در امتداد آن بشکنید

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

Team Topologies و بار شناختی حیاتی ​

به زبان ساده: یک تیم فقط به‌اندازه‌ای نرم‌افزار را می‌تواند صاحب شود که بفهمد؛ اندازهٔ مرز سرویس را با تیم بسنجید، نه برعکس.

بدفهمی رایج: «سرویس بیشتر برای هر تیم یعنی بهره‌وری.» صفحهٔ مفاهیم کلیدی Team Topologies: "Teams can only handle so much complexity before breaking down. Each new tool, responsibility or domain your team is given taxes their mental bandwidth."

تعریف: چهار نوع تیم و سه حالت تعامل Skelton و Pais، به همان صورتی که teamtopologies.com فهرست می‌کند:

نوع تیمتعریف (teamtopologies.com)پیامد برای مرز سرویس
Stream-aligned"aligned to a flow of work from (usually) a segment of the business domain"سرویس‌های کسب‌وکار را سر تا ته صاحب است؛ "You Built It, You Run It"
Platform"a grouping of other team types that provide a compelling internal product to accelerate delivery by Stream-aligned teams"صاحب CI/CD، broker، observability؛ مصرف سلف‌سرویس
Enabling"helps a Stream-aligned team to overcome obstacles. Also detects missing capabilities."صاحب هیچ سرویس production نیست؛ مربی‌گری می‌کند
Complicated-subsystem"where significant mathematics/calculation/technical expertise is needed"صاحب یک مؤلفهٔ تخصصی (موتور قیمت‌گذاری، codec ویدیو)
حالت تعاملتعریفمرز معمول
Collaboration"working together for a defined period of time to discover new things"مرز هنوز جابه‌جا می‌شود؛ موقت
X-as-a-Service"one team provides and one team consumes something 'as a Service'"API پایدار، سلف‌سرویس
Facilitation"one team helps and mentors another team"مرز زمان اجرا ندارد
text
     Team "Checkout" (6 people) owns: cart, orders, payments, invoices, emails, 4 DBs, Kafka setup
1    Incident at 02:00 in invoices; the on-call engineer has never touched it
2    Feature work stalls for a week of firefighting
3    Fix: invoices -> new Billing stream-aligned team; Kafka setup -> platform team (X-as-a-Service)
4    Checkout now owns cart + orders: two services it fully understands

سناریوی واقعی: تیم پنج‌نفره‌ای که صاحب ۲۲ میکروسرویس است (رایج بعد از تقسیم «یک سرویس برای هر entity»): بیشترشان هیچ‌وقت لمس نمی‌شوند و هیچ‌کس نمی‌تواند دیباگشان کند. مدل رتبه‌بندی یادگیری ماشین که صاحبش یک تیم complicated-subsystem است و تیم جست‌وجو آن را به‌صورت سرویس مصرف می‌کند. تیم platform که کلاستر broker آن اجازه می‌دهد هر تیم stream-aligned بدون یاد گرفتن عملیات Kafka رویداد منتشر کند.

راه درست: برای هر سرویس پیشنهادی بپرسید «کدام تیم صاحبش است و آیا بار کل آن تیم هنوز معقول است؟» فاولر: "the primary benefit of a platform is to reduce the cognitive load on stream-aligned teams". اگر جواب «هیچ‌کس» یا «تیمی که از قبل دوازده‌تا دارد» است، مرز غلط است، نه تیم.

Bounded context به‌عنوان نامزد مرز حیاتی ​

به زبان ساده: جایی که معنای یک واژه عوض می‌شود، احتمالاً مرزی هم آن‌جاست.

بدفهمی رایج: «یک bounded context مساوی یک میکروسرویس.» context مرز مدل است؛ می‌تواند یک سرویس، چند سرویس یا یک ماژول در monolith باشد. Lewis و Fowler: "there is a natural correlation between service and context boundaries"؛ همبستگی، نه این‌همانی.

تعریف: Evans (DDD Reference): "A description of a boundary (typically a subsystem, or the work of a particular team) within which a particular model is defined and applicable." فاولر: DDD می‌پذیرد که "total unification of the domain model for a large system will not be feasible or cost-effective"، و "Usually the dominant one is human culture, since models act as Ubiquitous Language, you need a different model when the language changes." جزئیات کامل مدل‌سازی در Bounded Context است.

text
     Word "Customer" in one shop
1    Sales:     prospect with a segment and a discount tier
2    Billing:   an account with a credit limit and payment method
3    Shipping:  a delivery address and a phone number
4    Support:   a person with tickets and a satisfaction score
     One Customer table with all fields = four teams editing one schema = implementation coupling

سناریوی واقعی: شرکت برق فاولر که «meter» در آن سه معنای متفاوت داشت؛ بازارگاهی که «Product» برای یک تیم آگهی کاتالوگ است و برای تیم دیگر واحد نگهداری انبار؛ بیمارستانی که «Patient» در پذیرش و در صورت‌حساب شناسه و چرخهٔ عمر متفاوت دارد (واژه‌های چندمعنا، Polyseme).

نشانهپیشنهاد مرز contextپیشنهاد همان context
یک واژه، ویژگی‌ها یا قاعده‌های متفاوتبله
کارشناس‌های متفاوتی که باید با آن‌ها مصاحبه کنیدبله
invariant از دو طرف رد می‌شود (باید اتمی باشد)بله
تغییرها همیشه با هم می‌رسندبله

راه درست: یک جلسهٔ Event Storming برگزار کنید، جاهایی را که زبان عوض می‌شود علامت بزنید و آن خط‌ها را نامزد مرز بدانید؛ بعد پیش از آوردن هر شبکه‌ای آن‌ها را با آزمون‌ها بسنجید.

راهبردهای تجزیه حیاتی ​

به زبان ساده: شش دلیل رایج برای گذاشتن یک خط در یک جای مشخص هست؛ مرزهای خوب معمولاً چندتایش را هم‌زمان برآورده می‌کنند.

بدفهمی رایج: «بر اساس entity بشکن: سرویس User، سرویس Product، سرویس Order.» سرویس‌های اسمی (entity) برش غلط کلاسیک‌اند: هر use case چندتایشان را لمس می‌کند. Dehghani دربارهٔ سرویس‌هایی که "driven by the existing normalized view of the data" هستند هشدار می‌دهد، که "almost always leads to a cambrian explosion of large number of anemic services for CRUD resources."

تعریف: راهبردها و منبعشان:

راهبردمنبعقاعده (نقل یا خلاصه)قوتضعف
بر اساس business capabilitymicroservices.io"Define services corresponding to business capabilities"، "something that a business does in order to generate value"پایدار: capabilityها کندتر از چارت سازمانی عوض می‌شوندنقشهٔ capability می‌تواند سیاسی شود
بر اساس subdomain / bounded contextmicroservices.io، Evans"Define services corresponding to Domain-Driven Design (DDD) subdomains"؛ core، supporting، genericزبان و مدل را دنبال می‌کنددانش دامنه لازم دارد
بر اساس volatilityHard Parts (code volatility)؛ Parnasپرتغییر را از پایدار جدا کنشعاع انفجار تغییر کوچک می‌شودتغییرپذیری با زمان جابه‌جا می‌شود
بر اساس مالکیت دادهNewman (درز دیتابیس)؛ microservices.io database per serviceیک نویسنده برای هر رکورد؛ در امتداد درز داده بشکنcoupling دیتابیس مشترک حذف می‌شودکوئری‌های میان‌دامنه مسیر تازه می‌خواهند
بر اساس نیاز مقیاسHard Parts ("Scalability and throughput")بخش‌هایی با بار بسیار متفاوت سرویس خودشان را می‌گیرندمقیاس مقرون‌به‌صرفهاغلب زودرس
بر اساس compliance / امنیتHard Parts ("Security")؛ Newman (امنیت به‌عنوان محرک شکستن)دادهٔ تنظیم‌شده یا حساس را جدا کندامنهٔ ممیزی کوچک‌تر (مثلاً PCI DSS)دادهٔ تنظیم‌شده باز هم به لاگ و event نشت می‌کند
text
     Online shop, one candidate per strategy
1    Capability:   Orders, Billing, Shipping, Catalog
2    Subdomain:    Pricing (core), Catalog (supporting), Email (generic -> buy SaaS)
3    Volatility:   Promotions rules change weekly -> separate from stable Orders
4    Data:         Billing is the only writer of invoices and credit
5    Scale:        Search serves 90% of reads -> own service + index
6    Compliance:   Card tokens in a payment vault service, nothing else sees a PAN

سناریوی واقعی: موتور قیمت‌گذاری تاکسی اینترنتی که برای volatility جدا شده (قاعده‌ها روزانه عوض می‌شوند)؛ خزانهٔ کارت که برای دامنهٔ PCI جدا شده؛ جست‌وجوی سایت خبری که برای مقیاس جدا شده؛ محصول B2B که بر اساس capability شکسته شده چون هر capability خریدار و نقشهٔ راه خودش را دارد.

راه درست: با capability یا subdomain نامزدها را پیدا کنید، بعد با چهار راهبرد دیگر خط را جابه‌جا کنید (volatility، داده، compliance) یا یک شکستن اضافه را توجیه کنید (مقیاس). خطی که فقط یک محرک دارد، و آن محرک «مقیاسی که شاید لازم شود» است، اولین خطی است که باید حذف شود.

آزمون‌های مرز حیاتی ​

به زبان ساده: شش آزمون سریع می‌گویند خط پیشنهادی دوام می‌آورد یا نه.

بدفهمی رایج: «یک بار در کارگاه بکشیم و تمام.» Monolith First فاولر: "even experienced architects working in familiar domains have great difficulty getting boundaries right at the beginning." این آزمون‌ها را با تغییر سیستم دوباره اجرا می‌کنید.

تعریف:

آزمونسؤالقبول وقتیرد وقتی
Information hiding (Parnas، Newman)سرویس می‌تواند درونیاتش را بی‌خبر دادن به کسی عوض کند؟schema و کد خصوصی‌اند؛ فقط قرارداد عمومی استدیگران جدول‌ها یا کلاس‌هایش را می‌خوانند
با هم تغییر می‌کنند، با هم می‌مانند (common closure)بیشتر تغییرهای X، Y را هم عوض می‌کنند؟کمتر از حدود ۱ در ۱۰ تغییر از خط رد می‌شودLewis و Fowler: "repeatedly changing two services together" یعنی ادغام
مرز تراکنش (Transaction boundary)invariantی هست که باید از دو طرف اتمی باشد؟invariantها درون یک سرویس می‌مانندNewman: اگر state "really, really wants to be kept consistent, do everything you can to avoid splitting it up"
ثقل داده (Data gravity)بیشتر داده‌ای که یک use case لازم دارد همین الان کجاست؟دادهٔ use case یک طرف استهر درخواست از سه سرویس داده جمع می‌کند
آزمون interface پرحرف (Chatty)در هر درخواست کاربر چند فراخوانی از خط رد می‌شود؟یک یا دو فراخوانی درشت، یا صفر (event)ده فراخوانی ریز؛ Lewis و Fowler: API راه دور "need to be coarser-grained"
مالکیت یک تیمدقیقاً یک تیم می‌تواند صاحبش باشد؟یک تیم، با on-call«مشترک بین تیم A و B»
text
     Candidate split: Orders | Inventory
1    Info hiding:   Inventory exposes Reserve(sku, qty) only            pass
2    Change:        12 of 80 order-related commits also touched inventory  borderline (15%)
3    Transaction:   "never sell what we do not have" spans both          FAIL -> needs reservation + saga
4    Data gravity:  checkout needs stock levels on every request         FAIL -> cache/replica of stock
5    Chatty:        1 reserve call per order                              pass
6    Ownership:     Fulfilment team owns inventory                         pass
     Decision: split, but design the reservation saga and stock projection first, or keep them together

سناریوی واقعی: سامانهٔ بلیت‌فروشی که موجودی صندلی و سفارش یک invariant مشترک دارند (رزرو دوباره ممنوع) و کنار هم ماندند؛ CMS که «مقاله» و «نظر» آزمون تغییر را رد کردند و بعد از یک سال ادغام شدند؛ جداسازی پرداخت که هر شش آزمون را قبول شد چون یکپارچه‌سازی PSP زبان و تیم خودش را داشت.

راه درست: شش آزمون را روی کاغذ برای هر خط نامزد اجرا کنید؛ هر رد یک راهکار نام‌دار (saga، projection، ادغام) پیش از شکستن لازم دارد. آزمون تغییر را واقعاً با ابزار change coupling روی تاریخچهٔ monolith اجرا کنید.

انواع coupling میان سرویس‌ها حیاتی ​

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

بدفهمی رایج: «پیام‌رسانی ناهم‌زمان coupling را حذف می‌کند.» coupling زمانی را حذف می‌کند. مصرف‌کننده‌ای که به همهٔ فیلدهای entity داخلی تولیدکننده وابسته است هنوز coupling پیاده‌سازی دارد، فقط یک broker وسطش هست.

تعریف: Newman در فصل اول Monolith to Microservices میان coupling دامنه، زمانی، پیاده‌سازی و استقرار فرق می‌گذارد (طرح فصل از صفحهٔ کتاب Newman؛ فهرست از یادداشت‌های یک خواننده، ثانویه). در این صفحه این‌طور تعریفشان می‌کنیم:

4. Implementation coupling (worst)A reads B's tables, uses B's classes, or both import a shared library with domain logicTax: B cannot change its schema or code without breaking A. Remedy: hide it; publish an API or event3. Deployment couplingA and B must ship together (release train, lockstep versions, shared artefact)Tax: one change waits for every team. Remedy: backward-compatible contracts, expand then contract2. Temporal couplingA can finish only while B is up and fast (synchronous call chain)Tax: availability multiplies, latency adds. Remedy: async events, local copies of data, timeouts1. Domain coupling (unavoidable)A needs something B does ("Billing needs to know an order was placed")Tax: small if the contract is small. Remedy: keep the published language narrow; one directioncost to changegrows upward
نوعتعریفمثالمالیات پنهانقابل‌قبول می‌شود وقتی
دامنه (Domain coupling)یک سرویس به کارکرد یا اطلاعاتی که دیگری می‌دهد نیاز داردBilling باید بداند سفارش‌ها ثبت شدندتغییر مفهوم مشترک موج می‌فرستدقرارداد کوچک، صریح و نسخه‌دار است
زمانی (Temporal coupling)هر دو باید در همان لحظه در دسترس باشند تا کار تمام شودOrders هم‌زمان Pricing را صدا می‌زنددسترس‌پذیری ضرب، تأخیر جمع، retry تشدیدطرف مقابل بسیار پایدار است یا فراخوانی اختیاری است
استقرار (Deployment coupling)سرویس‌ها باید با هم منتشر شوندOrders v5 همان روز Billing v7 را لازم داردهماهنگی انتشار؛ rollback دو سرویسهرگز میان تیم‌ها؛ درون دو پردازهٔ یک تیم اشکال ندارد
پیاده‌سازی (Implementation coupling)یک سرویس به نحوهٔ ساخت دیگری وابسته استجدول مشترک، مدل ORM مشترک، کتابخانهٔ دامنهٔ مشترکارائه‌دهنده نمی‌تواند refactor کند؛ schema عملاً API عمومی می‌شودهرگز از روی مرز سرویس
text
     Same feature, four couplings, four bills
1    Domain:          Billing reads OrderPlaced{order_id,total}          bill: one contract to version
2    Temporal:        Orders -> Pricing -> Tax, 3 x 99.9% up               bill: 99.7% at best, latencies add
3    Deployment:      Orders and Billing share a JAR with Invoice class    bill: every Invoice change = joint release
4    Implementation:  Orders SELECTs billing_invoices directly            bill: Billing cannot rename a column

سناریوی واقعی: تیمی که به Kafka مهاجرت کرد و entityهای JPA خودش را به‌صورت event منتشر کرد: coupling زمانی صفر، coupling پیاده‌سازی کامل (هر تغییر نام ستون مصرف‌کننده‌ها را می‌شکست). یک کتابخانهٔ «common» با Money، Customer و OrderStatus که ۳۰ سرویس از آن استفاده می‌کنند: coupling استقرار از راه ارتقای نسخه. صفحهٔ shared database در microservices.io دقیقاً همین هزینه‌ها را می‌شمارد: "Development time coupling" و "Runtime coupling".

راه درست: هدف «فقط coupling دامنه، و کوچک» است: یک published language (event یا قرارداد API) منتشر کنید که مدل داخلی شما نیست؛ خواندن‌ها را محلی کنید (event، projection) تا coupling زمانی برود؛ قراردادها را سازگار با عقب نگه دارید تا coupling استقرار برود؛ هرگز جدول یا کلاس دامنه را به اشتراک نگذارید تا coupling پیاده‌سازی برود.

Distributed monolith حیاتی ​

به زبان ساده: سیستمی که به‌صورت چند سرویس deploy می‌شود ولی هنوز باید مثل یکی تغییر کند، منتشر شود و دیباگ شود.

بدفهمی رایج: «distributed monolith یعنی monolithی که روی چند ماشین اجرا می‌شود.» monolithی که افقی مقیاس شده (چند نسخه از یک deployable) سالم است. مشکل، deployableهای متفاوت زیادی است که به‌اندازهٔ ماژول‌های یک برنامه به هم وابسته‌اند؛ هزینهٔ شبکه و عملیات را می‌دهید بی‌آنکه تغییر مستقل بگیرید.

تعریف: مجموعه‌ای از سرویس‌ها با coupling استقرار و پیاده‌سازی بالا میان خودشان، که با deploy هم‌قدم (Lockstep)، دیتابیس مشترک، زنجیرهٔ فراخوانی هم‌زمان و کتابخانهٔ مشترک (Shared library) حاوی منطق دامنه شناخته می‌شوند. Monolith to Microservices اثر Newman، distributed monolith را میان «monolithهای دیگر» می‌شمارد (یادداشت‌های خواننده، ثانویه)، و Lewis و Fowler هشدار می‌دهند که اگر مؤلفه‌ها تمیز ترکیب نشوند، "all you are doing is shifting complexity from inside a component to the connections between components."

Distributed monolithReal service boundariesorders-svcpricing-svctax-svcsyncsyncshared lib: domain models + rules (all import it)one shared databaseeveryone reads everyone's tablesrelease train: all deploy togethersymptoms: lockstep deploys, cascading outagesorders-svcoutboxbilling-svcACL + inboxbrokerOrderPlaced v1orders DBbilling DBcontract test in Orders' CI (Billing's expectations)each service deploys alone; Orders works while Billing is down
text
     Tuesday release of "add sales_region to orders"
1    09:00  Orders adds column orders.sales_region
2    09:10  Reporting service SELECTs orders.* and breaks (shared DB)
3    09:30  Billing's copy of shared-domain-lib Order class needs the field: lib v4.2 -> v4.3
4    11:00  Orders, Billing, Reporting rebuilt with lib 4.3; release train scheduled for 16:00
5    16:20  Pricing slow -> Orders slow -> checkout times out (sync chain)
6    16:40  Rollback must roll back three services together

سناریوی واقعی: شرکتی با ۴۰ «میکروسرویس» و یک پنجرهٔ انتشار هفتگی؛ استارتاپی که همهٔ سرویس‌هایش core-models را import می‌کنند؛ بانکی که هر سرویسش در هر درخواست سرویس مشتری را صدا می‌زند، پس قطعی سرویس مشتری یعنی قطعی کامل.

نشانه‌ها، روش تشخیص و درمان:

نشانهتشخیصآستانهٔ نگرانیدرمان
Deploy هم‌قدملاگ deploy: انتشارهایی با بیش از یک سرویس، یا runbookهای «اول B بعد A»بیش از حدود ۲۰٪ انتشارها هماهنگ‌شدهتغییر API به روش expand/contract؛ event نسخه‌دار
دیتابیس مشترکinformation_schema.role_table_grants؛ لاگ کوئری هر roleهر جدولی که دو role سرویس می‌نویسندschema + role برای هر سرویس؛ بعد دیتابیس برای هر سرویس
زنجیرهٔ فراخوانی هم‌زمانtrace توزیع‌شده: عمق و fan-out هر درخواستعمق بیش از ۳ روی مسیر بحرانیevent، projection محلی، ادغام جفت پرحرف
کتابخانهٔ مشترک با منطق دامنهگراف وابستگی: پکیج دامنه در ۲+ سرویسهر قاعدهٔ دامنه در کتابخانهٔ مشترککپی کد، انتشار قرارداد، یا ادغام
Change couplingدرجهٔ هم‌تغییری git میان سرویس‌هابیش از ۳۰٪ برای جفتی با ۵+ commit مشترکجابه‌جایی خط یا ادغام
On-call مشترکحادثه‌هایی که حلشان دو تیم لازم داردبیشتر حادثه‌هابازکشیدن مرز تا هر کدام یک صاحب داشته باشد

راه درست: اول اندازه بگیرید (سنجش سلامت مرز)، بعد سراغ گران‌ترین coupling بروید: پیاده‌سازی (جدول و کتابخانهٔ مشترک) قبل از استقرار، و استقرار قبل از زمانی. گاهی درمان درست ادغام سرویس‌ها در یک deployable با ماژول است: modular monolith مقصدی کاملاً مشروع است.

مالیات پنهان میکروسرویس مهم ​

به زبان ساده: هر مرز سرویس برای هر درخواست و هر تغییر اجاره می‌گیرد، چه متوجه بشوید چه نه.

بدفهمی رایج: «هزینهٔ میکروسرویس همان کلاستر Kubernetes است.» زیرساخت قلم دیدنی هزینه است. Microservice Premium فاولر: میکروسرویس‌ها "introduce complexity on their own account. This adds a premium to a project's cost and risk".

تعریف: مالیات پنهان جمع هزینه‌هایی است که از خود مرز می‌آیند، نه از قابلیت‌ها:

مالیاتاز کجا می‌آیداندازهٔ تقریبیچه کسی می‌پردازد
تأخیر (Latency)فراخوانی درون‌پردازه (نانوثانیه) به یک hop شبکه (کسری از میلی‌ثانیه تا چند میلی‌ثانیه) به‌علاوهٔ serialisation تبدیل می‌شودفاولر: فراخوانی راه دور "are orders of magnitude slower"کاربران، در هر درخواست
دسترس‌پذیری (Availability)وابستگی‌های زنجیره‌ای ضرب می‌شوندسه سرویس ۹۹٫۹٪ در زنجیره: 0.999^3 = 99.7%کاربران؛ SLO (SLA و بودجهٔ خطا)
سازگاری (Consistency)تراکنش ACID میان سرویس‌ها نیستsaga، جبران، outbox، idempotency (Saga، Outbox)توسعه‌دهنده‌ها، برای هر invariant میان‌سرویسی
دیباگیک درخواست از چند پردازه و لاگ می‌گذردtracing، correlation ID، تجمیع لاگمهندسان on-call
تستیکپارچگی روی شبکه رخ می‌دهدcontract test، محیط تست، fakeهمهٔ تیم‌ها، همهٔ pipelineها
زیرساختpipeline، image، secret، داشبورد برای هر سرویسخطی با تعداد سرویس‌هاتیم platform
On-callهر سرویس صاحبی لازم دارد که بیدار شودآدم، نه سروربار شناختی تیم‌ها
دادهٔ تکراریکپی محلی برای پرهیز از coupling زمانیذخیره‌سازی به‌علاوهٔ مدیریت کهنگیتوسعه‌دهنده‌ها، کاربران (خواندن کهنه)
نسخه‌گذاری (Versioning)قرارداد باید بدون هم‌قدمی تکامل یابدفیلد نسخه، پنجرهٔ deprecationتیم‌های تولیدکننده
text
     One checkout request, before and after a split into 5 services
1    Monolith:   1 process, 1 transaction, p99 120 ms, one log stream
2    Split:      5 hops x ~2-5 ms network + serialisation, p99 tail of the slowest hop dominates
3    Failure:    Pricing timeout -> retry x3 -> 3x load on a struggling service (cascading failure)
4    Debug:      5 log streams; without a trace ID, 40 minutes to find which hop failed

سناریوی واقعی: تیمی که p99اش بعد از جدا کردن سرویس قیمت‌گذاری که در هر صفحه چهار بار صدا زده می‌شد دو برابر شد؛ جریان پرداختی که برای جایگزینی یک COMMIT به outbox و inbox نیاز پیدا کرد؛ شرکتی که محیط تستش از production گران‌تر است چون هر تیم همهٔ سرویس‌ها را روشن لازم دارد.

راه درست: مالیات را پیش از شکستن قیمت بگذارید: فراخوانی‌ها در هر درخواست، invariantها در هر مرز، و سرویس‌ها برای هر تیم را بشمارید. فقط جایی بپردازید که سود (تغییر مستقل به دست تیم مستقل، مقیاس یا compliance جدا) بزرگ‌تر است. نیمهٔ زمان اجرا را در Cascading Failures و Timeouts، Retries و Jitter ببینید.

دانه‌بندی: integratorها، disintegratorها و nanoservice مهم ​

به زبان ساده: دو دسته نیرو یک سرویس را از هم می‌کشند یا دوباره به هم می‌چسبانند؛ اندازهٔ درست جایی است که تعادل برقرار شود.

بدفهمی رایج: «میکروسرویس باید زیر N خط کد باشد.» Hard Parts: "Granularity is not defined by the number of classes or lines of code in a service, but rather what the service does."

تعریف: Ford و همکاران شش disintegrator ("When should I consider breaking apart a service into smaller parts?") و چهار integrator ("When should I consider putting services back together?") می‌شمارند:

Disintegrator (شکستن)سؤال (Hard Parts)Integrator (ادغام)سؤال (Hard Parts)
Service scope and function"Is the service doing too many unrelated things?"Database transactions"Is an ACID transaction required between separate services?"
Code volatility"Are changes isolated to only one part of the service?"Workflow and choreography"Do services need to talk to one another?"
Scalability and throughput"Do parts of the service need to scale differently?"Shared code"Do services need to share code among one another?"
Fault tolerance"Are there errors that cause critical functions to fail within the service?"Data relationships"can the data it uses be broken apart as well?"
Security"Do some parts of the service need higher security levels than others?"
Extensibility"Is the service always expanding to add new contexts?"

Nanoservice سرویسی است که سربارش (قرارداد، pipeline، on-call، hop شبکه) از ارزش کاری که می‌کند بیشتر است: CRUD یک entity، یک تابع، «سرویسی» که همیشه همراه یک سرویس دیگر صدا زده می‌شود. nanoservice چیزی است که وقتی فقط disintegratorها را ببینید به دست می‌آید.

text
     Notification service: email, SMS, postal letter (Hard Parts example, summarised)
1    Scope:        all three "notify a customer"            -> cohesive, keep together
2    Volatility:   postal letter code changes weekly         -> disintegrator: split postal out?
3    Fault:        email provider outage kills SMS too        -> disintegrator
4    Integrators:  no shared transaction, no shared data      -> nothing pulls back
     Result: postal letter separate; email + SMS maybe separate; one "Notification" boundary stays a team's

سناریوی واقعی: فروشگاهی با cart-service، cart-item-service و cart-total-service جدا (nanoservice: هر درخواست هر سه را صدا می‌زند)؛ مدل تشخیص تقلب که برای مقیاس و تیم متفاوت از پرداخت جدا شده؛ تابع address-validation که به‌صورت کتابخانه یا فراخوانی SaaS بهتر است تا سرویس.

راه درست: برای هر شکستن، disintegratorهایی که توجیهش می‌کنند و integratorهایی که مخالفش هستند را فهرست کنید و هر دو را در ADR بنویسید (تصمیم‌های معماری). Hard Parts دو معیار اندازه هم پیشنهاد می‌کند: تعداد statementها و تعداد عملیات عمومی؛ برای یافتن داده‌های پرت به کارشان ببرید، نه به‌عنوان هدف.

Context mapping میان سرویس‌ها مهم ​

به زبان ساده: وقتی مرزها را دارید، رابطهٔ دو طرف هر کدام را نام ببرید: چه کسی خودش را با چه کسی تطبیق می‌دهد و از چه راهی.

بدفهمی رایج: «همهٔ یکپارچه‌سازی‌ها یکی‌اند: API را صدا بزن.» رابطه تعیین می‌کند هزینهٔ تغییر را چه کسی می‌دهد. تیم پایین‌دستی که با مدل بالادستی همرنگ می‌شود (conformist) هر تغییر بالادست را به ارث می‌برد؛ تیمی با لایهٔ ضدفساد (Anticorruption layer) یک بار، در همان لایه، می‌پردازد.

تعریف: الگوهای context map از Evans، به عبارت DDD Reference، در کاربرد برای سرویس‌ها (مدل‌سازی کامل در Context Map و الگوهای یکپارچه‌سازی):

الگوعبارت DDD Reference (کوتاه)به‌عنوان رابطهٔ سرویسcouplingی که می‌ماند
Partnership"forge a partnership between the teams in charge of the two contexts"دو تیم تغییر interface را با هم برنامه‌ریزی و منتشر می‌کنندcoupling استقرار با توافق؛ موقت نگهش دارید
Shared kernel"Designate with an explicit boundary some subset of the domain model that the teams agree to share. Keep this kernel small."یک پکیج قرارداد کوچک مشترک (شناسه‌ها، کد ارز)coupling پیاده‌سازی، کوچک و صریح
Customer/supplier"downstream priorities factor into upstream planning"contract test مصرف‌کننده در CI تأمین‌کننده اجرا می‌شودcoupling دامنه، محافظت‌شده با تست
Conformist"slavishly adhering to the model of the upstream team"پایین‌دست مدل event بالادست را همان‌طور استفاده می‌کندپایین‌دست هر تغییر بالادست را جذب می‌کند
Anticorruption layer (ACL)"create an isolating layer to provide your system with functionality of the upstream system in terms of your own domain model"یک مترجم در لبهٔ مصرف‌کنندهتغییرهای بالادست در ACL متوقف می‌شوند
Open host service (OHS)"Define a protocol that gives access to your subsystem as a set of services. Open the protocol"یک API یا جریان event عمومی و نسخه‌دارفقط coupling دامنه، برای مصرف‌کنندگان زیاد
Published language"Use a well-documented shared language ... as a common medium of communication"schema رویداد / سند OpenAPIواژگان مشترک، نه کد مشترک
Separate ways"Declare a bounded context to have no connection to the others at all"بدون یکپارچه‌سازی؛ در صورت نیاز تکرارهیچ
OrdersOHS + published languageorders.order_placed.v1Catalogproduct datashared kernelBillingdownstreamcustomer/supplierACLShippingdownstreamconformistRecommendationsseparate waysno integrationPSPexternalpaymentsU → DU → D
text
     OrderPlaced crossing three relationships
1    Orders (OHS) publishes orders.order_placed.v1 (published language)
2    Billing (customer/supplier + ACL) translates it to ChargeRequest; its contract test runs in Orders' CI
3    Shipping (conformist) stores the event fields as-is; accepts it changes when Orders changes
4    Orders renames total_cents in v2; Billing changes one ACL function; Shipping changes its schema

سناریوی واقعی: شرکتی که یک ERP بیست‌ساله را پشت ACL می‌پیچد تا سرویس‌های تازه هیچ‌وقت نام جدول‌هایش را نبینند؛ ارائه‌دهندگان پرداخت (Stripe، Adyen) به‌عنوان open host service که هر فروشنده در برابرشان یا conformist است یا ACL می‌سازد؛ دو تیم در partnership در فصل اول یک محصول تازه که وقتی API جا افتاد به customer/supplier می‌روند.

راه درست: نقشه را برای سرویس‌هایتان بکشید و روی هر یال برچسب بگذارید. پیش‌فرض: OHS + published language در بالادست و ACL در پایین‌دست؛ partnership و shared kernel را استثناهای کوچک و کوتاه‌عمر بدانید.

تکامل مرز: ادغام، شکستن، strangler fig، tactical forking مهم ​

به زبان ساده: مرزها کشف می‌شوند، نه ابلاغ؛ پس برای جابه‌جا کردنشان برنامه داشته باشید.

بدفهمی رایج: «ادغام دوبارهٔ سرویس‌ها یعنی اعتراف به شکست.» Lewis و Fowler آن را بازخورد عادی طراحی می‌دانند: "If you find yourself repeatedly changing two services together, that's a sign that they should be merged." و توضیح می‌دهند چرا روی شبکه سخت‌تر است: "Moving code is difficult across service boundaries, any interface changes need to be coordinated between participants".

تعریف: چهار حرکت:

حرکتچه وقتچطورمنبع
ادغام (Merge)change coupling بالا، جفت پرحرف، invariant مشترک، یک تیم صاحب هر دویکی را پشت API موجود در دیگری ادغام کن؛ pipeline دوم را بازنشسته کنLewis و Fowler؛ integratorهای Hard Parts
شکستن (Split)یک disintegrator برقرار است و تیمی می‌تواند صاحب بخش تازه شوداول مرز ماژول، بعد داده، بعد پردازهدرزهای Newman؛ Monolith First فاولر
Strangler figجایگزینی سیستم قدیمی تکه به تکهترافیک یک capability را به کد تازه ببر؛ رشد بده تا قدیمی تمام شودفاولر: "begins with small additions" و میزبان را تدریجی جایگزین می‌کند (Strangler Fig)
Tactical forkingmonolith درهم بدون مؤلفه‌های تمیزکل codebase را کپی کن، آنچه سرویس تازه لازم ندارد را حذف کنHard Parts؛ Thoughtworks Radar (مارس ۲۰۲۲)

تجزیهٔ مبتنی بر مؤلفه (Component-based decomposition)، رویکرد دیگر Hard Parts، برای monolithهایی است که از قبل مؤلفه‌های قابل‌تشخیص دارند: مؤلفه‌ها را شناسایی، اندازه‌گیری و یکپارچه کن، بعد جدایشان کن. tactical forking برای حالت برعکس است: Thoughtworks Radar آن را "one possible alternative to the more common approach of fully modularizing the codebase first" می‌خواند که در آن "a team can create a new fork of the codebase and use that to address and extract one particular concern or area while deleting the unnecessary code."

text
     Tactical forking: extracting Billing from a tangled monolith
1    Copy the monolith repo -> billing-svc
2    Route /billing/* to billing-svc; the monolith keeps the rest
3    In billing-svc: delete controllers, jobs, tables not reachable from billing paths (iterate until tests pass)
4    In the monolith: delete billing code once traffic is fully moved
5    Two smaller codebases; dead code removed on both sides; data split last

سناریوی واقعی: وب‌سایت Guardian (که Lewis و Fowler مثال می‌زنند) که قابلیت‌های تازه را به‌صورت سرویس دور هستهٔ monolith رشد می‌دهد؛ تیمی که بعد از اندازه‌گیری ۷۰٪ change coupling، cart و checkout را ادغام کرد؛ بانکی که یک سیستم batch روی mainframe را محصول به محصول strangle می‌کند.

راه درست: تا جایی که می‌شود جابه‌جایی مرز را ارزان نگه دارید: مرز ماژول و schema برای هر ماژول پیش از پردازه (Modular Monolith). وقتی جدا می‌کنید، توصیهٔ Dehghani صدق می‌کند: "Go Macro First, then Micro"، و "Capability and not Code" را جدا کنید.

سنجش سلامت مرز تکمیلی ​

به زبان ساده: مرزهای بد را پیش از آنکه در جلسه‌ها حس کنید، در لاگ deploy، traceها و تاریخچهٔ git می‌بینید.

بدفهمی رایج: «گراف import، coupling ما را نشان می‌دهد.» فقط coupling ایستا را نشان می‌دهد. دو سرویس ممکن است هیچ import متقابلی نداشته باشند و باز در هر commit با هم تغییر کنند، چون یک مفهوم، یک جدول یا یک تیم مشترک دارند. مستندات CodeScene: "Change Coupling means that two (or more) modules change together over time."

تعریف: سه خانوادهٔ معیار مرز:

معیارچه می‌سنجدچطور جمع کنیمسالمناسالم
نسبت coupling استقرار (Deploy coupling ratio)انتشارهایی که انتشار سرویس دیگری را در همان پنجره لازم داشتندرویدادهای deploy هر سرویس، گروه‌بندی بر اساس تیکت تغییرزیر ۱۰٪بالای ۲۰٪ یا وجود «release train»
تناوب deploy مستقلهر سرویس چند بار تنها منتشر می‌شودلاگ deploy هر pipelineروزانه یا بیشتر برای سرویس‌های فعالفقط در تاریخ انتشار مشترک
عمق / fan-out در call graphhopهای هم‌زمان در هر درخواست کاربرtrace (OpenTelemetry)، نمای گراف سرویسعمق ۱ تا ۲ روی مسیر بحرانیعمق بیش از ۳، یا چرخه
فراخوانی میان‌سرویسی در هر درخواستپرحرفیتعداد span در trace۰ تا ۲۱۰+
درجهٔ change couplingدو ماژول چند بار در یک commit تغییر می‌کنندتحلیل git log (ابزار پایین)زیر حدود ۲۰٪ میان سرویس‌هابالای ۳۰٪ با ۵+ commit مشترک
coupling میان‌تیمیchange coupling وقتی ماژول‌ها مال تیم‌های متفاوت‌اندchange coupling + CODEOWNERSکمزیاد: CodeScene می‌گوید "coordination costs in the organization might soar"
نویسنده‌های یک جدولroleهای سرویس با حق نوشتن روی یک جدولinformation_schema.role_table_grants۱۲+
text
     Monthly boundary review, 15 minutes
1    go run ./cmd/changecoupling -repo . -depth 2 -since "3 months ago"
2    services/cart <-> services/checkout   shared 41  degree 72%   -> merge candidate
3    Traces: checkout p99 path depth 5 (cart, pricing, promo, tax, stock) -> make promo/tax async or local
4    Deploys: 9 of 31 releases bundled cart+checkout                          -> confirms (1)
5    Action: ADR-0021 "merge cart into checkout"; revisit in 3 months

سناریوی واقعی: تیمی که با change coupling روی تاریخچهٔ monolithش اولین استخراج را انتخاب کرد (ماژولی با کمترین وابستگی به بقیه، همان توصیهٔ Newman: "pull out the seam that is least depended on")؛ تیم platform که داشبورد «درصد deploy تنها» را برای هر سرویس منتشر می‌کند؛ بازبینی معماری که یک شکستن را رد کرد چون دو ماژول در ۶۰٪ commitها با هم تغییر کرده بودند.

راه درست: ابزار change coupling را روی repository اجرا کنید، جفت‌هایی را که از خط سرویس یا تیم رد می‌شوند جدا کنید و پنج‌تای اول را ماهانه کنار داده‌های deploy و trace بازبینی کنید. هشدار CodeScene صادق است: change coupling "is neither good nor bad; it all depends on what modules are coupled and for what reason".

سازوکار (Mechanics) ​

کشیدن مرز قدم به قدم حیاتی ​

text
     A boundary workshop (half a day, people who know the domain and the teams)
1    List business capabilities and subdomains (core / supporting / generic)
2    Event Storming: mark where the language changes -> candidate contexts
3    Overlay the org: which team would own each candidate? Any orphan or overloaded team?
4    Run the six heuristics on each line; mark FAILs
5    Run change coupling on history for the matching modules; mark pairs over 30%
6    Pick lines that pass; for each FAIL, name the mitigation or drop the line
7    Write one ADR per boundary: owner, data, contract, coupling accepted, revisit trigger
8    Implement as modules first; add arch tests; extract to a process only with a reason

اعمال وجه داده در دیتابیس ​

roleهای دیتابیس مرز داده را از یک قرارداد نانوشته به یک خطای سخت تبدیل می‌کنند. در PostgreSQL، یک schema و یک role ورود برای هر سرویس:

sql
-- PostgreSQL: each service owns one schema and gets one role. Nobody else can touch it.
CREATE ROLE orders_svc  LOGIN PASSWORD 'change-me';
CREATE ROLE billing_svc LOGIN PASSWORD 'change-me';
CREATE SCHEMA orders  AUTHORIZATION orders_svc;
CREATE SCHEMA billing AUTHORIZATION billing_svc;
REVOKE ALL ON SCHEMA orders  FROM PUBLIC;
REVOKE ALL ON SCHEMA billing FROM PUBLIC;

CREATE TABLE orders.orders (
  id text PRIMARY KEY, customer_id text NOT NULL, currency char(3) NOT NULL,
  total_cents bigint NOT NULL CHECK (total_cents >= 0), created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders.outbox (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, event_id text NOT NULL UNIQUE,
  event_type text NOT NULL, payload jsonb NOT NULL, published_at timestamptz
);
CREATE TABLE billing.invoices (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, account_ref text NOT NULL,
  amount_minor bigint NOT NULL CHECK (amount_minor > 0), currency char(3) NOT NULL,
  source_ref text NOT NULL, status text NOT NULL
);
CREATE TABLE billing.inbox (event_id text PRIMARY KEY, processed_at timestamptz NOT NULL DEFAULT now());

-- Health check: which roles can write which schema? More than one writer = shared-database coupling.
SELECT table_schema, grantee, string_agg(DISTINCT privilege_type, ',') AS privileges
FROM information_schema.role_table_grants
WHERE table_schema IN ('orders', 'billing') AND privilege_type IN ('INSERT', 'UPDATE', 'DELETE')
GROUP BY table_schema, grantee
ORDER BY table_schema, grantee;

MySQL درون یک database، schema ندارد؛ معادلش یک database برای هر سرویس است (CREATE DATABASE billing) و GRANT ALL ON billing.* TO 'billing_svc'@'%'، بدون هیچ grantی برای orders_svc. در SQL Server از schema با GRANT ... ON SCHEMA::billing TO billing_svc استفاده کنید؛ در Oracle یک کاربر schema برای هر سرویس.

پیام‌های خطایی که وقتی مرز اعمال شده می‌بینید ​

کجاپیاممعنا
PostgreSQLERROR: permission denied for schema billing (SQLSTATE 42501)role سرویس Orders خواست schema سرویس Billing را بخواند: مرز ایستاد
MySQLERROR 1142 (42000): SELECT command denied to user 'orders_svc'@'%' for table 'invoices'همان، با عبارت MySQL
کامپایلر Gouse of internal package ... not allowedinternal/ ماژول دیگری import شده
تست معماری Go (این صفحه)orders/x.go imports academy/service-boundaries/billing (forbidden: orders may only share the published language)قاعدهٔ مرز شکسته شد
contract test در Go (این صفحه)billing needs field "total_cents"; provider no longer sends itتولیدکننده قرارداد مصرف‌کننده را شکست
Pest arch()expectation شکست‌خورده با نام کلاس و namespace ممنوع (عبارت دقیق به نسخهٔ Pest بستگی دارد؛ تأیید نشده)مرز ماژول شکسته شد
Pact (اگر استفاده کنید)شکست verification با نام تعامل و فیلد ناجورقرارداد مصرف‌کننده‌محور شکسته شد

Go ​

مثال جاری دو مرز در یک فروشگاه است: Orders (ثبت سفارش) و Billing (صدور صورت‌حساب). اول شکل غلط، بعد شکل درست، بعد تست‌ها و ابزار سنجش. ماژول در docs/snippets/architecture/service-boundaries/go است؛ go vet ./... و go test ./... پاس می‌شوند.

غلط: جدول مشترک و زنجیرهٔ هم‌زمان ​

Checkout جدول‌های Billing را می‌خواند (coupling پیاده‌سازی)، پیش از جواب دادن اول Pricing و بعد Tax را صدا می‌زند (coupling زمانی)، و ردیف صورت‌حساب Billing را درون تراکنش خودش درج می‌کند، که فقط چون دیتابیس مشترک است کار می‌کند. همهٔ پله‌های نردبان این‌جا حاضرند:

go
// Package wrong shows the distributed-monolith shape: the Orders service
// reads and writes Billing's tables and calls two services synchronously
// before it can answer. It compiles and works on a good day.
package wrong

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
)

// Checkout is Orders' handler. Every line below couples it to another team.
type Checkout struct {
	DB         *sql.DB      // the SAME database Billing and Customers use
	HTTP       *http.Client // used for synchronous calls in a chain
	PricingURL string
	TaxURL     string
}

func (c *Checkout) PlaceOrder(ctx context.Context, customerID int64, sku string, qty int) error {
	// Implementation coupling: Orders knows Billing's table and column names.
	var creditLimit, openCents int64
	err := c.DB.QueryRowContext(ctx, `
		SELECT b.credit_limit_cents, COALESCE(SUM(i.amount_cents), 0)
		FROM billing_accounts b
		LEFT JOIN billing_invoices i ON i.account_id = b.id AND i.status = 'open'
		WHERE b.customer_id = $1
		GROUP BY b.credit_limit_cents`, customerID).Scan(&creditLimit, &openCents)
	if err != nil {
		return fmt.Errorf("read billing tables: %w", err)
	}

	// Temporal coupling: Pricing and Tax must both be up, in sequence,
	// for Orders to accept a single order.
	price, err := c.getInt(ctx, c.PricingURL+"/prices/"+sku)
	if err != nil {
		return fmt.Errorf("pricing down, checkout down: %w", err)
	}
	tax, err := c.getInt(ctx, fmt.Sprintf("%s/tax?amount=%d", c.TaxURL, price*int64(qty)))
	if err != nil {
		return fmt.Errorf("tax down, checkout down: %w", err)
	}
	total := price*int64(qty) + tax
	if openCents+total > creditLimit {
		return fmt.Errorf("credit limit exceeded")
	}

	// One transaction across "two services": works only because they share
	// a database. Splitting the database later breaks this function.
	tx, err := c.DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()
	var orderID int64
	if err := tx.QueryRowContext(ctx,
		`INSERT INTO orders (customer_id, sku, qty, total_cents) VALUES ($1, $2, $3, $4) RETURNING id`,
		customerID, sku, qty, total).Scan(&orderID); err != nil {
		return err
	}
	// Orders writes Billing's invoice row directly: Billing's invariants are
	// now enforced (or not) by another team's code.
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO billing_invoices (account_id, order_id, amount_cents, status)
		 SELECT id, $2, $3, 'open' FROM billing_accounts WHERE customer_id = $1`,
		customerID, orderID, total); err != nil {
		return err
	}
	return tx.Commit()
}

func (c *Checkout) getInt(ctx context.Context, url string) (int64, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return 0, err
	}
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("%s: %s", url, strings.ToLower(resp.Status))
	}
	var v struct {
		Cents int64 `json:"cents"`
	}
	return v.Cents, json.NewDecoder(resp.Body).Decode(&v)
}

درست: published language، outbox، لایهٔ ضدفساد ​

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

go
// Package contracts is the published language between Orders and Billing.
// It contains data shapes only: no behaviour, no database code, no domain
// rules. Both services may import it; neither may import the other.
package contracts

import "time"

// OrderPlacedV1Type is the event type name on the wire (topic or routing key).
const OrderPlacedV1Type = "orders.order_placed.v1"

// OrderPlacedV1 is published by Orders after its local transaction commits
// (via the outbox). Fields are only ever added, never renamed or removed,
// within v1. A breaking change becomes orders.order_placed.v2.
type OrderPlacedV1 struct {
	EventID     string    `json:"event_id"`    // idempotency key for consumers
	OccurredAt  time.Time `json:"occurred_at"` // UTC
	OrderID     string    `json:"order_id"`
	CustomerID  string    `json:"customer_id"`
	Currency    string    `json:"currency"` // ISO 4217
	TotalCents  int64     `json:"total_cents"`
	Lines       []LineV1  `json:"lines"`
	SalesRegion string    `json:"sales_region,omitempty"` // added later; optional
}

// LineV1 is one order line as Orders describes it.
type LineV1 struct {
	SKU        string `json:"sku"`
	Quantity   int    `json:"quantity"`
	PriceCents int64  `json:"price_cents"`
}

Orders سفارش و رویداد را در یک تراکنش محلی در outbox خودش می‌نویسد. لازم نیست سرویس دیگری بالا باشد تا سفارش پذیرفته شود (بدون coupling زمانی)؛ relay را در Outbox ببینید:

go
// Package orders is the Orders boundary: it owns the orders tables and the
// outbox, and it tells the world what happened through the published
// language in package contracts. It never touches Billing's data.
package orders

import (
	"context"
	"crypto/rand"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"academy/service-boundaries/contracts"
)

// Line is Orders' own model of a line. It is not the wire type.
type Line struct {
	SKU        string
	Quantity   int
	PriceCents int64
}

// Service places orders. Its only dependency is its own database.
type Service struct {
	DB  *sql.DB
	Now func() time.Time
}

var ErrEmptyOrder = errors.New("orders: an order needs at least one line")

// Place stores the order and the OrderPlaced event in ONE local transaction.
// A relay (not shown; see the outbox chapter) publishes outbox rows later.
// No other service has to be up for an order to be accepted.
func (s *Service) Place(ctx context.Context, customerID, currency string, lines []Line) (string, error) {
	if len(lines) == 0 {
		return "", ErrEmptyOrder
	}
	var total int64
	for _, l := range lines {
		total += l.PriceCents * int64(l.Quantity)
	}
	orderID, eventID := newID("ord"), newID("evt")

	evt := contracts.OrderPlacedV1{
		EventID: eventID, OccurredAt: s.Now().UTC(),
		OrderID: orderID, CustomerID: customerID,
		Currency: currency, TotalCents: total,
	}
	for _, l := range lines {
		evt.Lines = append(evt.Lines, contracts.LineV1{SKU: l.SKU, Quantity: l.Quantity, PriceCents: l.PriceCents})
	}
	payload, err := json.Marshal(evt)
	if err != nil {
		return "", err
	}

	tx, err := s.DB.BeginTx(ctx, nil)
	if err != nil {
		return "", err
	}
	defer func() { _ = tx.Rollback() }()

	if _, err := tx.ExecContext(ctx,
		`INSERT INTO orders.orders (id, customer_id, currency, total_cents) VALUES ($1, $2, $3, $4)`,
		orderID, customerID, currency, total); err != nil {
		return "", fmt.Errorf("insert order: %w", err)
	}
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO orders.outbox (event_id, event_type, payload) VALUES ($1, $2, $3)`,
		eventID, contracts.OrderPlacedV1Type, payload); err != nil {
		return "", fmt.Errorf("insert outbox: %w", err)
	}
	return orderID, tx.Commit()
}

func newID(prefix string) string {
	b := make([]byte, 8)
	_, _ = rand.Read(b)
	return prefix + "-" + hex.EncodeToString(b)
}

Billing مدل خودش (ChargeRequest) را دارد و یک مترجم، یعنی ACL، که تنها کدی است که رویداد Orders را می‌شناسد:

go
// Package billing is the Billing boundary. It owns invoices and credit, and
// it learns about orders only through the published OrderPlaced event.
package billing

import (
	"errors"
	"fmt"

	"academy/service-boundaries/contracts"
)

// ChargeRequest is Billing's OWN model. Billing talks about "billable
// accounts" and "charges", not about orders and lines.
type ChargeRequest struct {
	IdempotencyKey string
	AccountRef     string
	AmountMinor    int64
	Currency       string
	SourceRef      string // "order:<id>", for the audit trail
}

var errInvalidEvent = errors.New("billing: invalid OrderPlaced event")

// TranslateOrderPlaced is the anticorruption layer (ACL): the only place in
// Billing that knows the shape of Orders' event. If Orders publishes v2,
// only this function (and a v2 twin) changes.
func TranslateOrderPlaced(e contracts.OrderPlacedV1) (ChargeRequest, error) {
	if e.EventID == "" || e.CustomerID == "" || e.TotalCents <= 0 || len(e.Currency) != 3 {
		return ChargeRequest{}, fmt.Errorf("%w: %+v", errInvalidEvent, e)
	}
	return ChargeRequest{
		IdempotencyKey: e.EventID,
		AccountRef:     "customer:" + e.CustomerID,
		AmountMinor:    e.TotalCents,
		Currency:       e.Currency,
		SourceRef:      "order:" + e.OrderID,
	}, nil
}

مصرف‌کننده‌اش از راه جدول inbox در همان تراکنش صورت‌حساب idempotent است (Idempotent Consumer و Inbox):

go
package billing

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

	"academy/service-boundaries/contracts"
)

// Consumer handles orders.order_placed.v1 messages from the broker.
type Consumer struct {
	DB *sql.DB // Billing's own database; Orders has no credentials for it
}

// Handle is idempotent: the event id is stored in an inbox table inside the
// same transaction as the invoice, so a redelivered message is a no-op.
func (c *Consumer) Handle(ctx context.Context, body []byte) error {
	var evt contracts.OrderPlacedV1
	if err := json.Unmarshal(body, &evt); err != nil {
		return fmt.Errorf("decode: %w", err) // poison message: route to DLQ
	}
	req, err := TranslateOrderPlaced(evt)
	if err != nil {
		return err
	}

	tx, err := c.DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()

	res, err := tx.ExecContext(ctx,
		`INSERT INTO billing.inbox (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING`,
		req.IdempotencyKey)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return nil // already processed
	}
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO billing.invoices (account_ref, amount_minor, currency, source_ref, status)
		 VALUES ($1, $2, $3, $4, 'open')`,
		req.AccountRef, req.AmountMinor, req.Currency, req.SourceRef); err != nil {
		return err
	}
	return tx.Commit()
}
go
package billing

import (
	"testing"

	"academy/service-boundaries/contracts"
)

func TestTranslateOrderPlaced(t *testing.T) {
	got, err := TranslateOrderPlaced(contracts.OrderPlacedV1{
		EventID: "evt-1", OrderID: "ord-9", CustomerID: "cus-7", Currency: "EUR", TotalCents: 4200,
	})
	if err != nil {
		t.Fatal(err)
	}
	want := ChargeRequest{IdempotencyKey: "evt-1", AccountRef: "customer:cus-7", AmountMinor: 4200, Currency: "EUR", SourceRef: "order:ord-9"}
	if got != want {
		t.Fatalf("got %+v, want %+v", got, want)
	}
	if _, err := TranslateOrderPlaced(contracts.OrderPlacedV1{EventID: "evt-2"}); err == nil {
		t.Fatal("expected an error for an incomplete event")
	}
}

تست‌هایی که مرز را صادق نگه می‌دارند ​

تست معماری importها را parse می‌کند و اگر Orders، Billing را import کند، Billing، Orders را، یا پکیج قراردادها رفتار پیدا کند (database/sql)، build را می‌شکند:

go
package boundaries_test

import (
	"go/parser"
	"go/token"
	"io/fs"
	"path/filepath"
	"strings"
	"testing"
)

// The rules of the boundary, as data. A boundary that exists only in a
// diagram is a wish; this test makes it a build failure.
var forbidden = map[string][]string{
	"orders":    {"academy/service-boundaries/billing"},
	"billing":   {"academy/service-boundaries/orders"},
	"contracts": {"academy/service-boundaries/orders", "academy/service-boundaries/billing", "database/sql"},
}

func TestBoundaries(t *testing.T) {
	for dir, bans := range forbidden {
		err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
			if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
				return err
			}
			f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
			if err != nil {
				return err
			}
			for _, imp := range f.Imports {
				p := strings.Trim(imp.Path.Value, `"`)
				for _, ban := range bans {
					if p == ban || strings.HasPrefix(p, ban+"/") {
						t.Errorf("%s imports %s (forbidden: %s may only share the published language)", path, p, dir)
					}
				}
			}
			return nil
		})
		if err != nil {
			t.Fatal(err)
		}
	}
}

Contract test مصرف‌کننده‌محور (Consumer-driven): Billing فیلدهایی را که می‌خواند در یک فایل JSON commit می‌کند؛ CI سرویس Orders یک رویداد واقعی encode می‌کند و هر فیلد و نوعش را بررسی می‌کند. تغییر نام total_cents build سرویس Orders را می‌شکند، نه production سرویس Billing را:

json
{
  "consumer": "billing",
  "provider": "orders",
  "event": "orders.order_placed.v1",
  "required_fields": {
    "event_id": "string",
    "occurred_at": "string",
    "order_id": "string",
    "customer_id": "string",
    "currency": "string",
    "total_cents": "number"
  }
}
go
package contracts

import (
	"encoding/json"
	"os"
	"testing"
	"time"
)

// consumerContract is what a consumer team commits to this repository:
// the fields it reads and their JSON types. The provider's CI runs this test,
// so Orders cannot remove or retype a field Billing relies on.
type consumerContract struct {
	Consumer       string            `json:"consumer"`
	Provider       string            `json:"provider"`
	Event          string            `json:"event"`
	RequiredFields map[string]string `json:"required_fields"`
}

func TestOrderPlacedV1SatisfiesBillingContract(t *testing.T) {
	raw, err := os.ReadFile("testdata/billing_expects_order_placed_v1.json")
	if err != nil {
		t.Fatal(err)
	}
	var c consumerContract
	if err := json.Unmarshal(raw, &c); err != nil {
		t.Fatal(err)
	}
	if c.Event != OrderPlacedV1Type {
		t.Fatalf("contract is for %q, provider publishes %q", c.Event, OrderPlacedV1Type)
	}

	// Encode a sample event exactly as the provider would publish it.
	sample := OrderPlacedV1{
		EventID: "evt-1", OccurredAt: time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC),
		OrderID: "ord-1", CustomerID: "cus-1", Currency: "EUR", TotalCents: 12000,
		Lines: []LineV1{{SKU: "BOOK-1", Quantity: 2, PriceCents: 6000}},
	}
	body, err := json.Marshal(sample)
	if err != nil {
		t.Fatal(err)
	}
	var wire map[string]any
	if err := json.Unmarshal(body, &wire); err != nil {
		t.Fatal(err)
	}

	for field, want := range c.RequiredFields {
		v, ok := wire[field]
		if !ok {
			t.Errorf("%s needs field %q; provider no longer sends it", c.Consumer, field)
			continue
		}
		if got := jsonType(v); got != want {
			t.Errorf("%s expects %q to be %s, provider sends %s", c.Consumer, field, want, got)
		}
	}
}

func jsonType(v any) string {
	switch v.(type) {
	case string:
		return "string"
	case float64:
		return "number"
	case bool:
		return "boolean"
	case []any:
		return "array"
	case map[string]any:
		return "object"
	default:
		return "null"
	}
}

سنجش: change coupling از git ​

changecoupling خروجی git log --name-only را می‌خواند، هر فایل را به یک ماژول (اولین -depth پوشه) نگاشت می‌کند، commitهای خیلی بزرگ را رد می‌کند (-max-files) و جفت‌هایی را که با هم تغییر می‌کنند چاپ می‌کند؛ درجه برابر است با commitهای مشترک تقسیم بر میانگین تعداد commitهای دو ماژول (ایدهٔ «sum of coupling» که CodeScene مستند کرده؛ فرمول ما نسخهٔ ساده‌ای از آن است):

go
// Command changecoupling finds modules that change together in git history.
// Two modules that keep appearing in the same commits are coupled, whatever
// the import graph says; if they belong to different services or teams,
// every such commit is a coordinated change across a boundary.
//
//	go run ./cmd/changecoupling -repo ~/src/shop -depth 2 -since "12 months ago"
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
	"os/exec"
	"sort"
	"strings"
)

// Pair is one coupled pair of modules.
type Pair struct {
	A, B          string
	Shared        int // commits that touched both
	RevsA, RevsB  int // commits that touched each
	DegreePercent int // Shared / average(RevsA, RevsB) * 100
}

// Options control the analysis.
type Options struct {
	Depth     int // path segments that name a module: 2 -> "services/orders"
	MinShared int // ignore pairs that co-changed fewer times
	MinDegree int // ignore pairs below this coupling percentage
	MaxFiles  int // skip huge commits (renames, formatting, dependency bumps)
}

func main() {
	repo := flag.String("repo", ".", "path to a git repository")
	since := flag.String("since", "12 months ago", "git --since value")
	var o Options
	flag.IntVar(&o.Depth, "depth", 2, "path segments that make up a module name")
	flag.IntVar(&o.MinShared, "min-shared", 5, "minimum commits shared by a pair")
	flag.IntVar(&o.MinDegree, "min-degree", 30, "minimum coupling degree in percent")
	flag.IntVar(&o.MaxFiles, "max-files", 50, "ignore commits touching more files than this")
	flag.Parse()

	cmd := exec.Command("git", "-C", *repo, "log", "--no-merges", "--since="+*since,
		"--name-only", "--pretty=format:@@%H")
	out, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := cmd.Start(); err != nil {
		fmt.Fprintln(os.Stderr, "git:", err)
		os.Exit(1)
	}
	commits, err := ReadCommits(out, o)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := cmd.Wait(); err != nil {
		fmt.Fprintln(os.Stderr, "git:", err)
		os.Exit(1)
	}

	pairs := Couple(commits, o)
	fmt.Printf("%-32s %-32s %7s %7s %7s %7s\n", "MODULE A", "MODULE B", "SHARED", "REVS A", "REVS B", "DEGREE")
	for _, p := range pairs {
		fmt.Printf("%-32s %-32s %7d %7d %7d %6d%%\n", p.A, p.B, p.Shared, p.RevsA, p.RevsB, p.DegreePercent)
	}
}

// ReadCommits parses `git log --name-only --pretty=format:@@%H` output into
// one set of module names per commit.
func ReadCommits(r io.Reader, o Options) ([]map[string]bool, error) {
	var commits []map[string]bool
	var files []string
	flush := func() {
		if len(files) == 0 || len(files) > o.MaxFiles {
			files = files[:0]
			return
		}
		mods := map[string]bool{}
		for _, f := range files {
			mods[ModuleOf(f, o.Depth)] = true
		}
		commits = append(commits, mods)
		files = files[:0]
	}
	sc := bufio.NewScanner(r)
	for sc.Scan() {
		line := strings.TrimSpace(sc.Text())
		switch {
		case strings.HasPrefix(line, "@@"):
			flush()
		case line != "":
			files = append(files, line)
		}
	}
	flush()
	return commits, sc.Err()
}

// ModuleOf maps a file path to its module: the first depth directories.
func ModuleOf(path string, depth int) string {
	parts := strings.Split(path, "/")
	if len(parts) <= 1 {
		return "(root)"
	}
	dirs := parts[:len(parts)-1]
	if len(dirs) > depth {
		dirs = dirs[:depth]
	}
	return strings.Join(dirs, "/")
}

// Couple counts revisions and shared commits and returns pairs sorted by
// degree, then by shared commits.
func Couple(commits []map[string]bool, o Options) []Pair {
	revs := map[string]int{}
	shared := map[[2]string]int{}
	for _, c := range commits {
		mods := make([]string, 0, len(c))
		for m := range c {
			mods = append(mods, m)
			revs[m]++
		}
		sort.Strings(mods)
		for i := 0; i < len(mods); i++ {
			for j := i + 1; j < len(mods); j++ {
				shared[[2]string{mods[i], mods[j]}]++
			}
		}
	}
	var pairs []Pair
	for k, n := range shared {
		avg := float64(revs[k[0]]+revs[k[1]]) / 2
		deg := int(float64(n) / avg * 100)
		if n < o.MinShared || deg < o.MinDegree {
			continue
		}
		pairs = append(pairs, Pair{A: k[0], B: k[1], Shared: n, RevsA: revs[k[0]], RevsB: revs[k[1]], DegreePercent: deg})
	}
	sort.Slice(pairs, func(i, j int) bool {
		if pairs[i].DegreePercent != pairs[j].DegreePercent {
			return pairs[i].DegreePercent > pairs[j].DegreePercent
		}
		if pairs[i].Shared != pairs[j].Shared {
			return pairs[i].Shared > pairs[j].Shared
		}
		return pairs[i].A+pairs[i].B < pairs[j].A+pairs[j].B
	})
	return pairs
}
go
package main

import (
	"strings"
	"testing"
)

const sampleLog = `@@c1
services/orders/place.go
services/billing/invoice.go
@@c2
services/orders/place.go
services/billing/invoice.go
@@c3
services/orders/cancel.go
@@c4
services/catalog/search.go
@@c5
services/orders/place.go
services/billing/credit.go
`

func TestCouple(t *testing.T) {
	o := Options{Depth: 2, MinShared: 2, MinDegree: 30, MaxFiles: 50}
	commits, err := ReadCommits(strings.NewReader(sampleLog), o)
	if err != nil {
		t.Fatal(err)
	}
	pairs := Couple(commits, o)
	if len(pairs) != 1 {
		t.Fatalf("want 1 pair, got %+v", pairs)
	}
	p := pairs[0]
	// billing changed in 3 commits, orders in 4, together in 3: 3 / 3.5 = 85%.
	if p.A != "services/billing" || p.B != "services/orders" || p.Shared != 3 || p.DegreePercent != 85 {
		t.Fatalf("unexpected pair %+v", p)
	}
}

func TestModuleOf(t *testing.T) {
	cases := map[string]string{
		"README.md":                        "(root)",
		"services/orders/place.go":         "services/orders",
		"services/orders/internal/db/x.go": "services/orders",
		"app/Modules/Billing/Invoice.php":  "app/Modules",
	}
	for in, want := range cases {
		if got := ModuleOf(in, 2); got != want {
			t.Errorf("ModuleOf(%q) = %q, want %q", in, got, want)
		}
	}
}

نگاه Go ​

قابلیت Goکدام وجه مرز را پوشش می‌دهدتوضیح
package و internal/رفتار، information hidinginternal/ را کامپایلر اعمال می‌کند؛ درونیات سرویس حتی در monorepo خصوصی می‌ماند
پکیج contracts فقط با typePublished languageبدون متد منطقی، بدون database/sql؛ با arch_test.go بررسی می‌شود
interface سمت مصرف‌کنندهcoupling دامنه کوچک می‌ماندمصرف‌کننده آنچه لازم دارد را اعلام می‌کند؛ ارائه‌دهنده importش نمی‌کند
database/sql با یک DSN برای هر سرویسدادههر binary فقط اعتبارنامهٔ schema خودش را دارد
go/parser در تست‌هاFitness functionقاعدهٔ import به‌صورت تست شکست‌خورده
رفت‌وبرگشت encoding/json در تستقراردادنام و نوع فیلدهای wire format، در CI ارائه‌دهنده
os/exec + git logسنجش سلامتchange coupling بدون ابزار بیرونی
یک cmd/<svc> برای هر deployableاستقرارهمین پکیج‌ها می‌توانند یک binary (modular monolith) یا چندتا باشند

Pact پیاده‌سازی Go هم دارد (pact-go) اگر جریان مصرف‌کننده‌محور مبتنی بر broker را ترجیح می‌دهید؛ مستندات Pact، contract testing را "checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a 'contract'" تعریف می‌کند. نسخهٔ stdlib بالا همان ایده است بدون broker.

Laravel ​

همان دو مرز در یک برنامهٔ Laravel 13 (PHP 8.4) که به‌صورت ماژول زیر App\Modules ساختار یافته. PHP روی ماشین نگارش نصب نیست؛ کد بازبینی شده، اجرا نشده.

غلط: یک controller، دادهٔ سه تیم ​

php
<?php

namespace App\Http\Controllers;

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

/**
 * The distributed-monolith shape in Laravel: "Orders" reads and writes
 * Billing's tables and calls Pricing and Tax synchronously, in a chain.
 */
class CheckoutController
{
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'customer_id' => ['required', 'integer'],
            'sku' => ['required', 'string'],
            'qty' => ['required', 'integer', 'min:1'],
        ]);

        // Implementation coupling: Billing's table and column names.
        $credit = DB::table('billing_accounts as b')
            ->leftJoin('billing_invoices as i', function ($join) {
                $join->on('i.account_id', '=', 'b.id')->where('i.status', 'open');
            })
            ->where('b.customer_id', $data['customer_id'])
            ->groupBy('b.credit_limit_cents')
            ->selectRaw('b.credit_limit_cents, COALESCE(SUM(i.amount_cents), 0) AS open_cents')
            ->first();

        // Temporal coupling: two synchronous hops before we can answer.
        $price = Http::timeout(2)->get(config('services.pricing.url')."/prices/{$data['sku']}")
            ->throw()->json('cents');
        $tax = Http::timeout(2)->get(config('services.tax.url').'/tax', ['amount' => $price * $data['qty']])
            ->throw()->json('cents');
        $total = $price * $data['qty'] + $tax;

        abort_if($credit === null || $credit->open_cents + $total > $credit->credit_limit_cents, 422, 'Credit limit exceeded');

        // One transaction across two teams' tables: only possible because
        // the database is shared. This is the line that blocks the split.
        $orderId = DB::transaction(function () use ($data, $total) {
            $orderId = DB::table('orders')->insertGetId([
                'customer_id' => $data['customer_id'],
                'sku' => $data['sku'],
                'qty' => $data['qty'],
                'total_cents' => $total,
            ]);
            DB::table('billing_invoices')->insert([
                'account_id' => DB::table('billing_accounts')->where('customer_id', $data['customer_id'])->value('id'),
                'order_id' => $orderId,
                'amount_cents' => $total,
                'status' => 'open',
            ]);

            return $orderId;
        });

        return response()->json(['id' => $orderId], 201);
    }
}

درست: published language، outbox، ACL، job idempotent ​

Published language یک کلاس final readonly با wire format صریح است:

php
<?php

namespace App\Modules\Orders\Contracts;

/**
 * Published language between Orders and its consumers. Data only: no
 * Eloquent, no facades, no business rules. Fields are added, never renamed
 * or removed, within v1; a breaking change becomes OrderPlacedV2.
 */
final readonly class OrderPlacedV1
{
    public const TYPE = 'orders.order_placed.v1';

    /**
     * @param  list<array{sku: string, quantity: int, price_cents: int}>  $lines
     */
    public function __construct(
        public string $eventId,
        public string $occurredAt,
        public string $orderId,
        public string $customerId,
        public string $currency,
        public int $totalCents,
        public array $lines,
        public ?string $salesRegion = null,
    ) {}

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return array_filter([
            'event_id' => $this->eventId,
            'occurred_at' => $this->occurredAt,
            'order_id' => $this->orderId,
            'customer_id' => $this->customerId,
            'currency' => $this->currency,
            'total_cents' => $this->totalCents,
            'lines' => $this->lines,
            'sales_region' => $this->salesRegion,
        ], fn ($v) => $v !== null);
    }

    /** @param  array<string, mixed>  $p */
    public static function fromArray(array $p): self
    {
        return new self(
            eventId: (string) $p['event_id'],
            occurredAt: (string) $p['occurred_at'],
            orderId: (string) $p['order_id'],
            customerId: (string) $p['customer_id'],
            currency: (string) $p['currency'],
            totalCents: (int) $p['total_cents'],
            lines: $p['lines'] ?? [],
            salesRegion: $p['sales_region'] ?? null,
        );
    }
}

Orders فقط روی اتصال خودش می‌نویسد (orders، در config/database.php با اعتبارنامهٔ schema سفارش‌ها) و رویداد را در همان DB::connection('orders')->transaction() در outbox ثبت می‌کند:

php
<?php

namespace App\Modules\Orders;

use App\Modules\Orders\Contracts\OrderPlacedV1;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Orders' use case. It writes only to the "orders" connection (its own
 * schema and credentials) and records the event in its outbox in the same
 * transaction. A relay publishes outbox rows to the broker afterwards.
 */
final class PlaceOrder
{
    /**
     * @param  list<array{sku: string, quantity: int, price_cents: int}>  $lines
     */
    public function __invoke(string $customerId, string $currency, array $lines): string
    {
        throw_if($lines === [], \InvalidArgumentException::class, 'An order needs at least one line.');

        $total = array_sum(array_map(fn (array $l) => $l['price_cents'] * $l['quantity'], $lines));
        $orderId = (string) Str::ulid();

        $event = new OrderPlacedV1(
            eventId: (string) Str::uuid(),
            occurredAt: now('UTC')->toIso8601ZuluString(),
            orderId: $orderId,
            customerId: $customerId,
            currency: $currency,
            totalCents: $total,
            lines: $lines,
        );

        DB::connection('orders')->transaction(function () use ($orderId, $customerId, $currency, $total, $event) {
            $db = DB::connection('orders');
            $db->table('orders')->insert([
                'id' => $orderId,
                'customer_id' => $customerId,
                'currency' => $currency,
                'total_cents' => $total,
            ]);
            $db->table('outbox')->insert([
                'event_id' => $event->eventId,
                'event_type' => OrderPlacedV1::TYPE,
                'payload' => json_encode($event->toArray(), JSON_THROW_ON_ERROR),
            ]);
        });

        return $orderId;
    }
}

مدل خود Billing و لایهٔ ضدفسادش:

php
<?php

namespace App\Modules\Billing\Acl;

/** Billing's own vocabulary: accounts and charges, not orders and lines. */
final readonly class ChargeRequest
{
    public function __construct(
        public string $idempotencyKey,
        public string $accountRef,
        public int $amountMinor,
        public string $currency,
        public string $sourceRef,
    ) {}
}
php
<?php

namespace App\Modules\Billing\Acl;

use App\Modules\Orders\Contracts\OrderPlacedV1;
use InvalidArgumentException;

/**
 * Anticorruption layer: the only Billing class that knows Orders' event.
 */
final class OrderPlacedTranslator
{
    public function translate(OrderPlacedV1 $e): ChargeRequest
    {
        if ($e->eventId === '' || $e->customerId === '' || $e->totalCents <= 0 || strlen($e->currency) !== 3) {
            throw new InvalidArgumentException("Invalid OrderPlaced event {$e->eventId}");
        }

        return new ChargeRequest(
            idempotencyKey: $e->eventId,
            accountRef: "customer:{$e->customerId}",
            amountMinor: $e->totalCents,
            currency: $e->currency,
            sourceRef: "order:{$e->orderId}",
        );
    }
}

مصرف‌کننده یک job صف‌شده است (ShouldQueue با trait Queueable، $tries و backoff())؛ insertOrIgnore روی inbox تعداد ردیف‌های درج‌شده را برمی‌گرداند، پس تحویل دوباره ۰ درج می‌کند و زود برمی‌گردد:

php
<?php

namespace App\Modules\Billing\Jobs;

use App\Modules\Billing\Acl\OrderPlacedTranslator;
use App\Modules\Orders\Contracts\OrderPlacedV1;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

/**
 * Billing's consumer for orders.order_placed.v1. The payload arrives as an
 * array (from the outbox relay or a broker consumer); Billing writes only to
 * its own "billing" connection. Idempotent through the inbox table.
 */
final class HandleOrderPlaced implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    /** @param  array<string, mixed>  $payload */
    public function __construct(public array $payload) {}

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

    public function handle(OrderPlacedTranslator $acl): void
    {
        $charge = $acl->translate(OrderPlacedV1::fromArray($this->payload));

        DB::connection('billing')->transaction(function () use ($charge) {
            $db = DB::connection('billing');
            $fresh = $db->table('inbox')->insertOrIgnore(['event_id' => $charge->idempotencyKey]);
            if ($fresh === 0) {
                return; // redelivery: already invoiced
            }
            $db->table('invoices')->insert([
                'account_ref' => $charge->accountRef,
                'amount_minor' => $charge->amountMinor,
                'currency' => $charge->currency,
                'source_ref' => $charge->sourceRef,
                'status' => 'open',
            ]);
        });
    }
}

تست‌هایی که مرز را صادق نگه می‌دارند ​

تست معماری Pest: "Architecture testing enables you to specify expectations that test whether your application adheres to a set of architectural rules" (pestphp.com). not->toUse وابستگی را ممنوع می‌کند؛ toOnlyBeUsedIn "enables you to limit the usage of a specific class or set of classes to only particular parts of your application" (مستندات آرگومان رشته‌ای نشان می‌دهند؛ شکل آرایه‌ای که این‌جا استفاده شده با مستندات تأیید نشده):

php
<?php

// Pest architecture tests: the boundary rules fail the build, not a review.

arch('orders never reaches into billing')
    ->expect('App\Modules\Orders')
    ->not->toUse('App\Modules\Billing');

arch('billing sees only the published language of orders')
    ->expect('App\Modules\Billing')
    ->not->toUse([
        'App\Modules\Orders\PlaceOrder',
        'App\Modules\Orders\Models',
    ]);

arch('the published language is plain data')
    ->expect('App\Modules\Orders\Contracts')
    ->not->toUse([
        'Illuminate\Support\Facades\DB',
        'Illuminate\Database\Eloquent\Model',
    ]);

arch('only the ACL touches the orders contract inside billing')
    ->expect('App\Modules\Orders\Contracts')
    ->toOnlyBeUsedIn([
        'App\Modules\Orders',
        'App\Modules\Billing\Acl',
        'App\Modules\Billing\Jobs',
    ]);

contract test همان فایل قرارداد مصرف‌کنندهٔ نسخهٔ Go را می‌خواند:

php
<?php

use App\Modules\Orders\Contracts\OrderPlacedV1;

// Consumer-driven contract: Billing commits the fields it reads; Orders' CI
// runs this test, so a rename or removal fails before it ships.

it('still satisfies what billing expects from orders.order_placed.v1', function () {
    $contract = json_decode(
        file_get_contents(base_path('contracts/billing_expects_order_placed_v1.json')),
        true,
        flags: JSON_THROW_ON_ERROR,
    );

    expect($contract['event'])->toBe(OrderPlacedV1::TYPE);

    $wire = json_decode(json_encode((new OrderPlacedV1(
        eventId: 'evt-1',
        occurredAt: '2026-11-25T10:00:00Z',
        orderId: 'ord-1',
        customerId: 'cus-1',
        currency: 'EUR',
        totalCents: 12000,
        lines: [['sku' => 'BOOK-1', 'quantity' => 2, 'price_cents' => 6000]],
    ))->toArray()), true);

    foreach ($contract['required_fields'] as $field => $type) {
        expect($wire)->toHaveKey($field);
        $actual = match (true) {
            is_string($wire[$field]) => 'string',
            is_int($wire[$field]), is_float($wire[$field]) => 'number',
            is_bool($wire[$field]) => 'boolean',
            is_array($wire[$field]) => 'array',
            default => 'null',
        };
        expect($actual)->toBe($type, "billing expects {$field} to be {$type}");
    }
});

نگاه Laravel ​

قابلیت Laravelکدام وجه مرز را پوشش می‌دهدتوضیح
چند اتصال در config/database.php، DB::connection('billing')دادهیک اتصال و کاربر DB برای هر ماژول/سرویس؛ grant اعمالش می‌کند
namespace ماژول + service providerرفتاریک provider برای هر ماژول سیم‌کشی می‌کند؛ کس دیگری داخل نمی‌شود
eventها با ShouldDispatchAfterCommitزمانی (درون‌پردازه)مستندات events در Laravel 13: این interface را پیاده کنید تا event فقط بعد از commit تراکنش dispatch شود
job و listener صف‌شده (ShouldQueue، $tries، backoff())زمانیکار ادامه پیدا می‌کند وقتی مصرف‌کننده کند یا خاموش است
insertOrIgnore، کلید یکتاIdempotencyالگوی inbox بدون پکیج اضافه
Pest arch()Fitness functionnot->toUse، toOnlyBeUsedIn، ignoring
Http::timeout()->retry()زمانی، وقتی sync اجتناب‌ناپذیر استفراخوانی را محدود کن؛ هرگز سه‌تا را روی مسیر درخواست زنجیر نکن
Event::fake()، Queue::fake()تسترویدادهای منتشرشدهٔ یک ماژول را بدون مصرف‌کننده تست کن (تست سیستم‌های پیام‌رسان)

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

دو سرویس یک دیتابیس مشترک دارند ​

راه‌حلچطورمزیتهزینه / محدودیت
schema + role برای هر سرویسschemaهای جدا، یک role نویسنده برای هر کدام؛ grant بقیه گرفته می‌شودارزان، فوری، قابل‌اعمالهمان سرور: محدودیت منابع و قطعی مشترک
view دیتابیس به‌عنوان قرارداد خواندنارائه‌دهنده view منتشر می‌کند؛ مصرف‌کننده فقط آن را می‌خواندچیدمان جدول پنهان می‌شودهنوز coupling زمان اجرا؛ Newman: "Useful only for read-only" (یادداشت خواننده)
API یا event + projection محلیمصرف‌کننده کپی خودش را از eventها نگه می‌داردcoupling زمان اجرا و پیاده‌سازی می‌رودسازگاری نهایی؛ کد projection
دیتابیس برای هر سرویسinstance یا کلاستر جداجداسازی کاملکوئری میان‌دامنه به گزارش‌گیری یا CQRS می‌رود (مالکیت داده)

زنجیرهٔ فراخوانی هم‌زمان روی مسیر بحرانی ​

راه‌حلچطورمزیتهزینه / محدودیت
Event-carried stateمصرف‌کننده آنچه لازم دارد را از eventها ذخیره می‌کنددر زمان درخواست فراخوانی‌ای نیستپنجرهٔ دادهٔ کهنه
فرمان ناهم‌زماندرخواست را بپذیر، بعداً تمام کنقطعی طرف مقابل کاربر را متوقف نمی‌کندUX باید حالت «در انتظار» داشته باشد
ادغام جفت پرحرفیک سرویس، فراخوانی درون‌پردازهhop و قرارداد حذف می‌شوندسرویس بزرگ‌تر؛ مالکیت را بسنجید
محدود کردن فراخوانیtimeout، retry با jitter، circuit breaker، fallbackآسیب محدود می‌شودهنوز coupling زمانی (Circuit Breaker)

کتابخانهٔ مشترک با منطق دامنه ​

راه‌حلچطورمزیتهزینه / محدودیت
کد را کپی کنهر سرویس نسخهٔ خودش از قاعده را داردارتقای هم‌قدم نیستقاعده‌ها ممکن است واگرا شوند (گاهی درست: contextهای متفاوت)
پکیج قرارداد فقط با داده منتشر کنtype، شناسه، enum؛ بدون قاعدهکوچک، پایدار، صریح (یک shared kernel)با دقت نسخه‌گذاری کنید
قاعده را به یک سرویس منتقل کنبقیه می‌پرسند یا گوش می‌دهندیک صاحب برای قاعدهcoupling دامنهٔ تازه
کتابخانه‌های فنی را نگه دارlogging، tracing، کلاینت HTTPاشکالی ندارد: معنای دامنه ندارندآهنگ ارتقا هنوز مهم است

deploy هم‌قدم و release train ​

راه‌حلچطورمزیتهزینه / محدودیت
Expand and contractفیلد تازه را اضافه کن، مصرف‌کننده‌ها را منتقل کن، قدیمی را بعداً حذف کنانتشار هماهنگ لازم نیستتغییر دومرحله‌ای، تکرار موقت
event و API نسخه‌دارorder_placed.v1 و .v2 کنار هممصرف‌کننده‌ها با سرعت خودشان می‌آیندتولیدکننده مدتی هر دو را اجرا می‌کند
contract test مصرف‌کننده‌محورانتظار مصرف‌کننده‌ها در CI ارائه‌دهنده اجرا می‌شودتغییر شکننده پیش از deploy گرفته می‌شودفایل‌های قرارداد برای نگهداری
ادغام سرویس‌هایی که همیشه با هم منتشر می‌شوندیک deployableصادق دربارهٔ couplingشعاع انفجار بزرگ‌تر

سرویس‌هایی که بر اساس entity شکسته شده‌اند ​

راه‌حلچطورمزیتهزینه / محدودیت
برش دوباره بر اساس capabilityentityها را بر اساس use caseهایی که عوضشان می‌کنند گروه کنقابلیت‌ها در یک سرویس فرود می‌آیندمهاجرت داده میان سرویس‌ها
ادغام در modular monolithماژول‌ها برش منطقی را نگه می‌دارندتراکنش برمی‌گردددوباره یک deployable
سرویس entity نازک فقط برای subdomain عمومیمثلاً دفترچهٔ نشانی بدون قاعدهکم‌تغییری آن را بی‌خطر می‌کندبرای entityهای هسته به‌ندرت صدق می‌کند

انتخاب ​

وضعیترویکرد پیشنهادی مرزتکنیک اضافهدلیل
یک تیم، محصول تازهبدون مرز سرویس؛ ماژول در یک deployableتست معماری، ADRMonolith First فاولر؛ Conway: تیم کوچک به‌هرحال monolith می‌سازد
۲ تا ۴ تیم، یک محصولModular monolith با یک ماژول برای هر تیمschema + role برای هر ماژول، CODEOWNERSمرزها ارزان و پیش از شبکه یاد گرفته می‌شوند
تیم‌ها به انتشار همدیگر گیر کرده‌اندماژولی با بیشترین تغییر مستقل را جدا کنگزارش change coupling برای انتخابشاول کم‌وابسته‌ترین درز (Newman)
یک بخش مقیاس بسیار متفاوت می‌خواهدفقط همان بخش را بشکنشاید replica خواندنی یا ایندکس جست‌وجو کافی باشدdisintegrator مقیاس، بقیه لازم نیست
دادهٔ تنظیم‌شده (کارت، سلامت)در سرویس و ذخیره‌گاه خودش جدا کنتوکن‌سازی؛ بدون دادهٔ تنظیم‌شده در eventدامنهٔ compliance کوچک می‌شود
سرویس‌های زیادی همیشه با هم deploy می‌شوندادغامشان کن یا قراردادها را درست کنexpand/contract، event نسخه‌دارdistributed monolith را حذف کن
سیستم قدیمی، monolith درهمtactical forking یا strangler figمسیریابی بر اساس capabilityماژولار کردن اول ممکن است سال‌ها طول بکشد
سیستم قدیمی با مؤلفه‌های روشنComponent-based decompositionمؤلفه‌ها را اندازه بگیر، بعد جدا کنریسک کمتر از fork
تیم پربارسرویس را به تیم تازه یا دیگر بده، یا سرویس‌ها را ادغام کنTeam Topologies: تیم platform یا complicated-subsystemبار شناختی حد است
دو context، یک invariantکنار هم نگه دارinvariant را به‌صورت یک aggregate مدل کنIntegrator: تراکنش دیتابیس

روند تصمیم برای یک خط پیشنهادی:

text
1  Can exactly one team own each side?                        no  -> do not split (or change teams first)
2  Is there an invariant that must be atomic across it?       yes -> keep together, or design a saga first
3  Do the two sides change together more than ~30% of time?   yes -> do not split; re-cut the line
4  Does a user request need more than 2 sync calls across?    yes -> add events/projections, or re-cut
5  Is there a disintegrator (volatility, scale, fault, security, scope)?  no -> keep as a module
6  Split: module -> schema+role -> contract + tests -> process

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

همان خط Orders/Billing در هر مرحله. آنچه عوض می‌شود، بهای رد شدن از آن است.

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

چطور ظاهر می‌شود: مرزها پوشه و namespaceاند؛ رد شدن یک فراخوانی تابع است؛ یک COMMIT سفارش و صورت‌حساب را پوشش می‌دهد.

ساده‌ترین استفادهٔ درست: حتی این‌جا هم به هر مرز آینده پکیج و facade خودش را بدهید. هنوز نشکنید: Conway می‌گوید تیمی دوازده‌نفره monolith می‌سازد و این خوب است.

مثال (ساده): فروشگاهی کوچک: OrderController درون یک DB::transaction، InvoiceService::createFor($order) را صدا می‌زند. یک ADR ثبت می‌کند «منطق Billing در app/Billing است».

مثال (شبیه production): محصولی ۲۵نفره که checkout و billing در آن پوشه‌اند. گزارش هفتگی change coupling، app/Orders ↔ app/Billing را ۱۲٪ نشان می‌دهد: خط واقعی است، ولی هنوز ارزش شبکه را ندارد.

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

چطور ظاهر می‌شود: ماژول‌ها صاحب جدول‌اند (schema + role)، facade دارند و event درون‌پردازه منتشر می‌کنند؛ تست معماری import درونیات را می‌بندد. بیشتر مرزها باید همین‌جا آزموده شوند پیش از آنکه توزیع شوند (Modular Monolith).

مثال: کد همین صفحه در یک برنامهٔ Laravel: PlaceOrder روی اتصال orders و outbox می‌نویسد؛ یک relay، HandleOrderPlaced را روی همان صف dispatch می‌کند؛ Billing فقط از راه اتصال billing می‌نویسد. تست‌های arch در Pest و contract test در یک CI اجرا می‌شوند.

text
     Modular monolith, one deployable
1    PlaceOrder: BEGIN (orders conn) -> INSERT orders.orders, orders.outbox -> COMMIT
2    Relay: SELECT unpublished outbox rows -> dispatch HandleOrderPlaced(payload) to queue
3    Worker: Billing ACL -> BEGIN (billing conn) -> INSERT inbox, invoices -> COMMIT
4    Billing down (worker stopped): orders still accepted; invoices catch up later

Microservices (میکروسرویس): مرز به شبکه تبدیل می‌شود ​

چه می‌ماند: published language، ACL، outbox و inbox، contract test. فقط انتقال عوض می‌شود: relay به‌جای صف محلی روی topic orders.order_placed.v1 در broker منتشر می‌کند.

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

text
     orders-svc and billing-svc, separate pipelines and databases
1    POST /orders -> orders-svc commits order + outbox (orders DB)
2    relay publishes orders.order_placed.v1 (event_id = idempotency key)
3    billing-svc consumes; ACL translates; inbox dedups; invoice committed (billing DB)
4    Orders deploys v2 of its API on Monday; Billing deploys on Thursday; contract test guarded both
     Failure path: broker down -> outbox rows accumulate; relay catches up; no order lost

دادهٔ توزیع‌شده: replica، cache و چندمنطقه‌ای ​

مرز کجا آزموده می‌شودچه می‌شکندپاسخ طراحی
Billing از projection سفارش‌ها می‌خواندprojection از جریان event عقب استحالت «در حال پردازش» نشان بده؛ job تطبیق؛ هشدار lag
replica خواندنی DB سفارش‌ها در دست سرویس گزارشگزارش به schema سرویس Orders وابسته می‌شودقرارداد گزارش منتشر کن (event به انبار داده)، نه دسترسی به replica
cache اعتبار مشتری در Ordersاعتبار کهنه سفارشی بالای سقف را تأیید می‌کندآن را یک اشاره بدان؛ Billing تصمیم نهایی را ناهم‌زمان با جبران می‌گیرد
چندمنطقه‌ای: Orders در دو منطقه فعالevent تکراری، جابه‌جایی ترتیبمصرف‌کنندهٔ idempotent؛ ترتیب بر اساس کلید (ترتیب و پارتیشن)
invariant میان‌سرویسیدر عمل ACID توزیع‌شده میان سرویس‌ها نیستsaga با جبران (Saga)؛ 2PC فقط درون یک محصول دیتابیس (Distributed SQL و 2PC)

مسیر مقیاس: ۱×، ۱۰×، ۱۰۰× ​

مقیاسمرزهاتمرین‌ها
۱× (یک تیم)ماژول در یک deployablefacade، ADR، تست معماری
۱۰× (۳ تا ۸ تیم)Modular monolith یا چند سرویس بر اساس capability، هر کدام یک صاحبschema + role برای هر ماژول، contract test، بازبینی change coupling، پایه‌های platform (CI، broker)
۱۰۰× (ده‌ها تیم)سرویس بر اساس capability گروه‌بندی‌شده بر اساس stream؛ تیم‌های platform و enablingTeam Topologies، context map به‌عنوان سند زنده، معیار coupling استقرار و trace برای هر مرز، بازبینی منظم ادغام/شکستن

آزمایشگاه: پیدا کن، درست کن، نگهبانی کن ​

همه‌چیز با نصب Go و بدون اینترنت اجرا می‌شود.

راه‌اندازی.

bash
cd docs/snippets/architecture/service-boundaries/go
go vet ./...
go test ./...
# ok  academy/service-boundaries
# ok  academy/service-boundaries/billing
# ok  academy/service-boundaries/cmd/changecoupling
# ok  academy/service-boundaries/contracts

قدم ۱: نسخهٔ غلط را بخوانید. wrong/checkout.go را باز کنید و روی هر بلوک نوع couplingش را بنویسید (پیاده‌سازی، زمانی، استقرار). انتظار: SELECT ... billing_accounts و INSERT INTO billing_invoices coupling پیاده‌سازی‌اند؛ دو فراخوانی getInt coupling زمانی؛ و تراکنش مشترک دلیلی است که سرویس‌ها نمی‌توانند مستقل deploy یا جدا شوند.

قدم ۲: مرز را عمداً بشکنید. _ "academy/service-boundaries/billing" را به importهای orders/orders.go اضافه کنید و از ریشهٔ ماژول go test . را اجرا کنید. انتظار: TestBoundaries با orders/orders.go imports academy/service-boundaries/billing (forbidden: ...) شکست می‌خورد. برگردانید.

قدم ۳: قرارداد را عمداً بشکنید. در contracts/orders_v1.go تگ JSON فیلد TotalCents را به "total" تغییر دهید و go test ./contracts را اجرا کنید. انتظار:

text
--- FAIL: TestOrderPlacedV1SatisfiesBillingContract
    contract_test.go: billing needs field "total_cents"; provider no longer sends it

برگردانید. حالا تغییر را به روش امن انجام دهید: فیلد اختیاری تازهٔ Discount int64 json:"discount_cents,omitempty" را اضافه کنید. انتظار: تست پاس می‌شود (گسترش بده، تغییر نام نده).

قدم ۴: repository خودتان را اندازه بگیرید.

bash
go run ./cmd/changecoupling -repo /path/to/your/repo -depth 2 -since "12 months ago" -min-shared 5
# MODULE A        MODULE B         SHARED  REVS A  REVS B  DEGREE
# services/cart   services/checkout     41      52      61     72%

برای برنامهٔ Laravel از -depth 3 استفاده کنید تا app/Modules/Billing یک ماژول حساب شود. انتظار: یک فهرست رتبه‌بندی‌شده. برای هر کدام از پنج جفت اول بنویسید: یک تیم یا دو تیم؟ یک سرویس یا دو سرویس؟

نتیجهیک سرویسدو سرویس، یک تیمدو سرویس، دو تیم
درجهٔ بالای ۳۰٪خوب: منسجمنامزد ادغاممشکل مرز: برش دوباره یا ادغام، ADR
درجهٔ ۱۰ تا ۳۰٪خوبزیر نظربررسی کنید قرارداد کوچک و نسخه‌دار باشد
درجهٔ زیر ۱۰٪شاید دو ماژول در یکی پنهان شده‌اندمرز خوبمرز خوب

قدم ۵: وجه داده را اعمال کنید. در یک PostgreSQL محلی، SQL بخش سازوکار را اجرا کنید، بعد با orders_svc وصل شوید و SELECT * FROM billing.invoices; را امتحان کنید. انتظار: ERROR: permission denied for schema billing. کوئری grantها را اجرا کنید. انتظار: هر schema دقیقاً یک نویسنده دارد.

قدم ۶ (Laravel، اختیاری). فایل‌های PHP را در یک پروژهٔ Laravel 13 با Pest کپی کنید، اتصال‌های orders و billing را در config/database.php اضافه کنید، php/contracts/ را در ریشهٔ پروژه کپی کنید و ./vendor/bin/pest را اجرا کنید. انتظار: چهار تست arch و contract test پاس می‌شوند؛ افزودن use App\Modules\Billing\Acl\ChargeRequest; به PlaceOrder.php تست «orders never reaches into billing» را می‌شکند.

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

باورواقعیت
مرز یعنی repository یا containerمرز چهار وجه دارد: داده، رفتار، تیم، استقرار؛ اشتراک هر کدام نشتش می‌دهد
قانون Conway دربارهٔ چارت سازمانی استدربارهٔ مسیرهای ارتباطی است؛ چه کسی واقعاً با چه کسی حرف می‌زند
سازمان‌دهی دوبارهٔ تیم‌ها معماری را درست می‌کندفاولر: با سیستم سخت موجود اصطکاک اضافه می‌کند؛ کد و سازمان را با هم عوض کنید
سرویس کوچک‌تر یعنی جداترcoupling و اندازه دو چیزند؛ nanoserviceها اغلب وابسته‌ترند
یک bounded context = یک میکروسرویسcontext می‌تواند ماژول، یک سرویس یا چند سرویس باشد؛ همبستگی، نه این‌همانی
پیام‌رسانی coupling را حذف می‌کندفقط coupling زمانی را؛ coupling دامنه و پیاده‌سازی می‌مانند
کتابخانهٔ دامنهٔ مشترک ارزان جلوی تکرار را می‌گیردcoupling استقرار و پیاده‌سازی در همهٔ import‌کننده‌ها می‌سازد
دیتابیس مشترک اشکالی ندارد اگر هر سرویس جدول‌های خودش را استفاده کندفقط اگر roleها اعمالش کنند؛ وگرنه join و write رخنه می‌کنند (microservices.io: coupling زمان توسعه و زمان اجرا)
بر اساس entity بشکن (سرویس User، Product، Order)use caseها از entityها رد می‌شوند؛ نتیجه سرویس‌های CRUD پرحرف و کم‌خون است
ادغام سرویس‌ها شکست استبازخورد عادی است: "repeatedly changing two services together" یعنی ادغام
هزینهٔ میکروسرویس زیرساخت استهزینه‌های بزرگ‌تر تأخیر، سازگاری، دیباگ، تست، on-call و نسخه‌گذاری‌اند
می‌شود مرزها را از اول درست کشیدفاولر: حتی معماران باتجربه "have great difficulty getting boundaries right at the beginning"
گراف import، coupling واقعی را نشان می‌دهدchange coupling از git، coupling منطقی‌ای را نشان می‌دهد که importها نمی‌بینند

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپارید
مرزداده + رفتار + تیم + استقرار؛ یک نویسنده برای هر رکورد
قانون Conwayسیستم از ساختار ارتباطی کپی می‌شود؛ مرز را روی یال‌های نازک ارتباط بگذارید
Inverse Conwayتیم را شکل بده تا سیستم شکل بگیرد؛ کد و سازمان را با هم عوض کن
Team Topologiesstream-aligned، platform، enabling، complicated-subsystem؛ collaboration، X-as-a-Service، facilitation
بار شناختیحد واقعی اندازهٔ آنچه یک تیم (و سرویس‌هایش) می‌تواند صاحب شود
راهبردهاcapability، subdomain، volatility، مالکیت داده، مقیاس، compliance؛ ترکیبشان کنید
آزمون‌هاinformation hiding، با هم تغییر کردن، مرز تراکنش، ثقل داده، آزمون پرحرفی، یک صاحب
نردبان couplingدامنه (کوچک نگه دار) < زمانی < استقرار < پیاده‌سازی (هرگز میان سرویس‌ها)
Distributed monolithdeploy هم‌قدم، DB مشترک، زنجیرهٔ sync، کتابخانهٔ دامنهٔ مشترک
مالیات پنهانتأخیر، دسترس‌پذیری (0.999^n)، سازگاری، دیباگ، تست، زیرساخت، on-call، دادهٔ تکراری، نسخه‌گذاری
دانه‌بندی۶ disintegrator در برابر ۴ integrator؛ اندازه یعنی کاری که می‌کند، نه تعداد خط
Context mapOHS + published language در بالادست، ACL در پایین‌دست؛ partnership و shared kernel کوچک و موقت
تکاملادغام با change coupling؛ شکستن اول از راه ماژول؛ strangler fig؛ tactical forking برای کد درهم
معیارهای سلامتنسبت coupling استقرار، عمق فراخوانی، درجهٔ change coupling، نویسنده‌های هر جدول
اعمالroleهای DB، تست معماری (Go parser، Pest arch())، contract test، CODEOWNERS

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

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

۱ — چهار وجه مرز سرویس و برای هر کدام یک نشت را نام ببرید. حیاتی ​

پاسخ

پاسخ: داده (سرویس دیگری جدول شما را می‌نویسد)، رفتار (قاعده کپی شده یا در کتابخانهٔ مشترک است)، تیم (دو تیم صاحبش هستند)، استقرار (release train). ببینید مرز چیست.

۲ — قانون Conway را به عبارت خودش بگویید و بگویید واقعاً دربارهٔ چیست. حیاتی ​

پاسخ

پاسخ: "organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations." دربارهٔ مسیرهای ارتباطی است، نه خود چارت سازمانی. ببینید قانون Conway.

۳ — چرا مانور معکوس Conway برای سیستم موجود درمان فوری نیست؟ مهم ​

پاسخ

پاسخ: با معماری سخت، تیم‌های تازه دیگر با کد جور نیستند و این "adds friction". سازمان و کد باید با هم و در قدم‌های کوچک عوض شوند. ببینید Inverse Conway.

۴ — کدام نوع تیم در Team Topologies برای کم کردن بار شناختی تیم‌های stream-aligned از راه یک محصول داخلی سلف‌سرویس وجود دارد، و از کدام حالت تعامل استفاده می‌کند؟ مهم ​

پاسخ

پاسخ: تیم platform، عمدتاً در حالت X-as-a-Service (و collaboration وقتی platform در حال شکل‌گیری است). ببینید Team Topologies.

۵ — سه سرویس با دسترس‌پذیری ۹۹٫۹٪ در یک زنجیرهٔ هم‌زمان صدا زده می‌شوند. بهترین دسترس‌پذیری درخواست چقدر است و کدام نوع coupling باعثش است؟ حیاتی ​

پاسخ

پاسخ: 0.999^3 ≈ 99.7%. coupling زمانی. ببینید مالیات پنهان.

۶ — چرا «event به‌جای فراخوانی» برای حذف coupling کافی نیست؟ حیاتی ​

پاسخ

پاسخ: coupling زمانی را حذف می‌کند. اگر event همان entity داخلی تولیدکننده باشد، coupling پیاده‌سازی می‌ماند؛ اگر نسخه‌ها باید با هم منتشر شوند، coupling استقرار می‌ماند. ببینید انواع coupling.

۷ — چهار نشانهٔ distributed monolith و برای هر کدام یک معیار بگویید. مهم ​

پاسخ

پاسخ: deploy هم‌قدم (سهم انتشارهای هماهنگ)، دیتابیس مشترک (نویسنده‌های هر جدول)، زنجیرهٔ sync (عمق trace)، کتابخانهٔ دامنهٔ مشترک (سرویس‌هایی که یک پکیج دامنه را import می‌کنند)؛ به‌علاوهٔ درجهٔ change coupling. ببینید Distributed monolith.

۸ — چهار integrator دانه‌بندی در Hard Parts را نام ببرید. تکمیلی ​

پاسخ

پاسخ: Database transactions، workflow and choreography، shared code، data relationships. ببینید دانه‌بندی.

۹ — Orders رویدادی منتشر می‌کند که Billing و Shipping مصرفش می‌کنند. Billing آن را به مدل خودش ترجمه می‌کند؛ Shipping همان‌طور ذخیره‌اش می‌کند. الگوهای context map را نام ببرید. مهم ​

پاسخ

پاسخ: Orders: open host service با published language. Billing: customer/supplier با anticorruption layer. Shipping: conformist. ببینید Context mapping.

۱۰ — کی tactical forking را به component-based decomposition ترجیح می‌دهید؟ تکمیلی ​

پاسخ

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

۱۱ — گزارش change coupling نشان می‌دهد cart و checkout که مال دو تیم‌اند در ۷۲٪ از ۴۱ commit مشترک با هم تغییر کرده‌اند. چه می‌کنید؟ مهم ​

پاسخ

پاسخ: آن را مشکل مرز بدانید: یا ادغامشان کنید (و مالکیت تیم‌ها را)، یا خط را دوباره ببرید تا مفهوم پرتغییر یک طرف بیفتد. در یک ADR ثبتش کنید. ببینید سنجش سلامت مرز.

۱۲ — contract test در Go در این صفحه از چه چیزی محافظت می‌کند و در CI چه کسی اجرا می‌شود؟ مهم ​

پاسخ

پاسخ: از حذف یا تغییر نوع فیلدی که مصرف‌کننده (Billing) می‌خواند به دست ارائه‌دهنده (Orders)؛ در CI ارائه‌دهنده اجرا می‌شود. ببینید Go.

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

واژهمعنا
مرز سرویس (Service boundary)خط دور دادهٔ یک سرویس، رفتارش، تیم صاحبش و واحد استقرارش
قانون Conway (Conway's law)سیستم از ساختار ارتباطی سازمانی که طراحی‌اش می‌کند کپی می‌شود (Conway 1968)
همریختی (Homomorphism)اصطلاح Conway برای نگاشت ساختارنگه‌دار میان سازمان و سیستم
مانور معکوس Conway (Inverse Conway manoeuvre)تغییر ساختار تیم برای تشویق معماری دلخواه (LeRoy و Simons، ۲۰۱۰)
Team Topologiesمدل Skelton و Pais: چهار نوع تیم، سه حالت تعامل
تیم Stream-alignedتیمی هم‌راستا با جریانی از کار از یک بخش دامنهٔ کسب‌وکار
تیم Platformتیمی که محصولی داخلی (CI، broker، observability) با مصرف سلف‌سرویس ارائه می‌دهد
تیم Enablingتیمی که به دیگران برای عبور از موانع مربی‌گری می‌کند
تیم Complicated-subsystemتیم صاحب مؤلفه‌ای که تخصص ویژه لازم دارد
X-as-a-Serviceحالت تعاملی که یک تیم پیشنهاد تیم دیگر را با همکاری کم مصرف می‌کند
Collaboration / facilitationحالت‌های تعامل: کار مشترک برای یک دوره؛ مربی‌گری
بار شناختی (Cognitive load)آنچه یک تیم باید بفهمد تا صاحب نرم‌افزارش باشد؛ حد اندازهٔ مرز
تیم دوپیتزایی (Two-pizza team)تیمی آن‌قدر کوچک که دو پیتزا سیرش کند (حداکثر حدود دوازده نفر)
Bounded contextمرزی که درون آن یک مدل و زبانش تعریف‌شده و معتبر است (Evans)
واژهٔ چندمعنا (Polyseme)واژه‌ای با چند معنای مرتبط در contextهای مختلف («مشتری»، «meter»)
Business capabilityکاری که کسب‌وکار برای ساختن ارزش انجام می‌دهد (microservices.io)
Subdomain (core، supporting، generic)بخشی از دامنهٔ کسب‌وکار، دسته‌بندی‌شده بر اساس میزان تمایزبخشی
تجزیه بر اساس تغییرپذیری (Volatility-based decomposition)شکستن بر اساس اینکه کد چند وقت یک بار تغییر می‌کند
مالکیت داده (Data ownership)یک سرویس منبع حقیقت و تنها نویسندهٔ یک تکه داده است
ثقل داده (Data gravity)use caseها و سرویس‌ها به سمت جایی می‌روند که دادهٔ لازمشان همان‌جاست
درز (Seam)بخشی از کد که می‌شود جداگانه رویش کار کرد (Feathers)؛ Newman برای یافتن مرز سرویس به کارش می‌برد
پنهان‌سازی اطلاعات (Information hiding)پنهان کردن تصمیم طراحی محتمل‌التغییر پشت یک interface (Parnas)
بستار مشترک (Common closure)چیزهایی که با هم تغییر می‌کنند کنار هم جا دارند
interface پرحرف (Chatty interface)مرزی که در هر درخواست فراخوانی‌های ریز زیادی از آن رد می‌شود
Domain couplingیک سرویس به کارکرد یا اطلاعاتی که دیگری می‌دهد نیاز دارد
Temporal couplingهر دو سرویس باید هم‌زمان در دسترس باشند تا کار تمام شود
Deployment couplingسرویس‌ها باید با هم منتشر شوند
Implementation couplingیک سرویس به درونیات دیگری (جدول، کلاس) وابسته است
Distributed monolithdeployableهای زیادی که آن‌قدر به هم وابسته‌اند که با هم تغییر، deploy و خراب می‌شوند
Deploy هم‌قدم / release trainانتشار هماهنگ چند سرویس با هم
مالیات پنهان / microservice premiumهزینه‌ای که خود مرزها اضافه می‌کنند: تأخیر، سازگاری، تست، on-call، زیرساخت
Granularity disintegratorنیرویی که شکستن سرویس را توجیه می‌کند (scope، volatility، مقیاس، تحمل خطا، امنیت، توسعه‌پذیری)
Granularity integratorنیرویی که کنار هم ماندن سرویس‌ها را توجیه می‌کند (تراکنش، workflow، کد مشترک، رابطهٔ داده)
Nanoserviceسرویسی که سربارش از کاری که می‌کند بیشتر است
سرویس entity (Entity service)سرویسی دور CRUD یک entity داده؛ معمولاً برش غلط
Context mapنمودار bounded contextها و رابطه‌های میانشان
Partnershipدو تیمی که با هم موفق یا ناکام می‌شوند و تکامل interface را هماهنگ می‌کنند
Shared kernelبخش کوچک و صریحاً مشترک از مدل و کد
Customer/supplierبالادست با اولویت‌های پایین‌دست برنامه‌ریزی می‌کند؛ تست‌های پایین‌دست در بالادست اجرا می‌شوند
Conformistپایین‌دست مدل بالادست را همان‌طور می‌پذیرد
لایهٔ ضدفساد (Anticorruption layer، ACL)مترجمی در پایین‌دست که مدل بالادست را از مدل خودش بیرون نگه می‌دارد
Open host service (OHS)پروتکلی که به‌صورت مجموعه‌ای از سرویس‌ها برای همهٔ یکپارچه‌کنندگان باز شده
Published languageزبان مشترک مستند (schema) برای یکپارچه‌سازی
Separate waysهیچ یکپارچه‌سازی میان دو context
Strangler figجایگزینی تدریجی سیستم قدیمی با رشد دادن بخش‌های تازه دور آن
Tactical forkingکپی کردن codebase درهم و حذف آنچه سرویس تازه لازم ندارد
Component-based decompositionشناسایی و یکپارچه کردن مؤلفه‌ها در monolith پیش از جدا کردنشان
Change couplingماژول‌هایی که در طول زمان در version control با هم تغییر می‌کنند
نسبت coupling استقرار (Deploy coupling ratio)سهم انتشارهایی که انتشار سرویس دیگری را هم لازم داشتند
Contract test / قرارداد مصرف‌کننده‌محور (Consumer-driven contract)هر طرف جداگانه در برابر یک قرارداد مستند آزموده می‌شود؛ مصرف‌کننده‌ها انتظارشان را منتشر می‌کنند
تست معماری / Fitness functionبررسی خودکاری که یک قاعدهٔ ساختاری هنوز برقرار است
Outbox / inboxجدول‌های محلی که انتشار و مصرف را با نوشتن کسب‌وکار اتمی می‌کنند
کلید idempotency (Idempotency key)شناسه‌ای که پردازش تکراری را بی‌اثر می‌کند
Expand and contractشکل تازه را اضافه کن، کاربران را منتقل کن، شکل قدیمی را بعداً حذف کن

منابع (References) ​

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