Microservices Architecture
"In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API." — James Lewis و Martin Fowler، Microservices، martinfowler.com، ۲۵ مارس ۲۰۱۴
خلاصه (Summary): میکروسرویس (Microservices) سبکی معماری است که در آن یک برنامه بهشکل چند سرویس کوچک ساخته میشود؛ هر سرویس مال یک تیم است، دادهٔ خودش را دارد و جداگانه مستقر میشود. این سبک استقلال تیمها و تغییر مستقل را میخرد و بهایش یک سیستم توزیعشده است. تمرکز (Focus): تعریف و نُه ویژگی (Lewis و Fowler)، استقرارپذیری مستقل (independent deployability) بهعنوان آزمون واقعی، دانهبندی (granularity) با نیروهای تجزیه و تجمیع Richards و Ford، ساختار تیمها، «حق بیمهٔ» میکروسرویس (microservice premium) و پیشنیازهایش، دغدغههای مشترک (cross-cutting) و پاسخ sidecar و service mesh، داده، ارتباط، تابآوری، observability، تست، استقرار و نسخهبندی، ضدالگوها، اینکه کی نباید سراغش رفت، و یک پلتفرم سفارشگیری کامل با Go و Laravel. هدف یادگیری (Learning goal): به هر سیستمی که اسمش «میکروسرویس» است نگاه کنید و بگویید واقعاً میکروسرویس است یا نه (آیا هر سرویس تنها مستقر میشود؟)، چه هزینهای دارد، کدام پیشنیازش کم است، کدام ضدالگو را نشان میدهد، و یک سرویس را درست بسازید: دادهٔ مالکیتدار، timeout، breaker، health، trace و contract test.
این فصل، فصل سبک در گروه AR 02 است: میگوید معماری میکروسرویس چیست و چه میطلبد. تصمیمهای پیرامونش در AR 03 فصل خودشان را دارند و این صفحه فقط خلاصه میکند و لینک میدهد: اینکه اصلاً این سبک را انتخاب کنیم یا نه (Monolith vs Microservices vs Modular Monolith)، کجا ببُریم (Service Boundaries)، سرویسها چطور حرف بزنند (Service Communication)، لبه و mesh (API Gateway, BFF & Service Mesh)، پیدا کردن نمونهها (Service Discovery) و داده (Data Ownership in Microservices). همسایههایش در AR 02 یکی SOA است که میکروسرویس از دلش بیرون آمد، و دیگری Modular Monolith که معمولاً قدم اول بهتری است.
نقشهٔ صفحه
| دنبال چه هستید | بروید به |
|---|---|
| کل سبک در سه جدول | همهچیز در یک دقیقه |
| چرا کسی هزینهٔ یک سیستم توزیعشده را میدهد | چرا وجود دارد |
| ونیز ۲۰۱۱، Lewis و Fowler ۲۰۱۴، واکنش ۲۰۲۳ | از کجا آمده |
| نُه ویژگی، یکییکی | نُه ویژگی |
| «میتوانم تنهایی مستقرش کنم؟» | استقرارپذیری مستقل |
| یک سرویس چقدر باید بزرگ باشد؟ | دانهبندی |
| تیمها، قانون Conway، two-pizza، stream-aligned | ساختار تیم |
| هزینه و آنچه اول لازم است | حق بیمه و پیشنیازها |
| auth، لاگ، tracing، config، secret؛ chassis، sidecar، mesh | دغدغههای مشترک |
| داده، ارتباط، تابآوری (کوتاه، با لینک) | داده، ارتباط، تابآوری |
| لاگ، متریک، trace، correlation ID، OpenTelemetry | Observability |
| unit، component، contract، end-to-end | تست |
| container، Kubernetes، rolling، blue/green، canary | استقرار |
| تغییر API بدون شکستن فراخوانندهها | نسخهبندی |
| distributed monolith و دوستانش | ضدالگوها |
| مسیر درخواست، تنظیمات، کدهای خطا | سازوکار |
| Orders، Catalog، Billing، Notifications با Go و Laravel | Go، Laravel |
| هر مشکل کلاسیک و راهحلش | حل مشکلات کلاسیک |
| برویم یا نه، و کی نه | انتخاب |
| از monolith تا سیستم توزیعشده | در معماری |
| یک سرویس را بکشید و breaker را ببینید | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
نُه ویژگی (Lewis و Fowler، ۲۰۱۴). هر سطر در نُه ویژگی باز میشود.
| # | ویژگی | به زبان ساده | مثال کوچک | بدون آن چه میشکند |
|---|---|---|---|---|
| 1 | مؤلفهسازی با سرویس (Componentization via services) | مؤلفهها پردازههای جدا هستند، نه کتابخانه | Catalog باینری و API خودش را دارد | یک تغییر یعنی استقرار دوبارهٔ همهچیز |
| 2 | سازمانیافته حول قابلیتهای کسبوکار (business capabilities) | برش بر اساس کاری که کسبوکار میکند، نه لایهٔ فنی | Billing، نه «تیم دیتابیس» | هر قابلیت از سه تیم رد میشود |
| 3 | محصول، نه پروژه (Products not projects) | تیمی که میسازد، اجرایش هم میکند، تا آخر عمر | تیم Billing کشیک (on-call) خودش را دارد | تحویل به «نگهداری»؛ کسی از production یاد نمیگیرد |
| 4 | نقطههای پایانی هوشمند، لولههای ساده (Smart endpoints and dumb pipes) | منطق در سرویسها؛ شبکه فقط پیام میبرد | RabbitMQ مسیر میدهد، مصرفکننده تصمیم میگیرد | یک ESB میشود monolith دوم و پنهان |
| 5 | حاکمیت غیرمتمرکز (Decentralized governance) | هر تیم ابزار مناسب خودش را برمیدارد | Catalog با Go، Billing با Laravel | یک stack به همهٔ مسئلهها تحمیل میشود |
| 6 | مدیریت دادهٔ غیرمتمرکز (Decentralized data management) | هر سرویس مالک دادهٔ خودش است؛ schema مشترک نداریم | billing_db فقط مال Billing است | تغییر schema به همهٔ تیمها گره میخورد |
| 7 | خودکارسازی زیرساخت (Infrastructure automation) | build، تست، تأمین و استقرار با pipeline | یک pipeline برای هر سرویس | بیست سرویس، بیست انتشار دستی |
| 8 | طراحی برای شکست (Design for failure) | هر فراخوانی راه دور میتواند شکست بخورد؛ برایش برنامه داشته باش | timeout برابر 300 ms + breaker روی Catalog | یک سرویس کُند کل سایت را میخواباند |
| 9 | طراحی تکاملی (Evolutionary design) | انتظار داشته باش سرویسها جدا، ادغام و جایگزین شوند | دو سرویسی که همیشه با هم عوض میشوند ادغام شوند | مرزهای غلط برای همیشه یخ میزنند |
چه میخرید و چه میپردازید.
| میخرید | میپردازید (حق بیمهٔ میکروسرویس) |
|---|---|
| استقرار مستقل برای هر تیم | یک deployment pipeline برای هر سرویس، بهعلاوهٔ contract test |
| مرز ماژول محکم (دور زدنش سخت است) | فراخوانی راه دور: تأخیر، serialization، شکست جزئی |
| مقیاسپذیری مستقل بخشهای داغ | eventual consistency بهجای یک تراکنش ACID |
| انتخاب فناوری برای هر سرویس | پیچیدگی عملیاتی: runtimeهای زیاد برای patch و پایش |
| جداسازی خطا، اگر برایش ساخته شده باشد | observability اجباری است، نه اختیاری |
| استقلال تیم، صف merge کوتاهتر | refactor بین سرویسها کند و هماهنگیطلب است |
ضدالگوها در یک جدول (جزئیات در ضدالگوها).
| ضدالگو | نشانه | راهحل در یک خط |
|---|---|---|
| Distributed monolith | سرویسها باید با هم منتشر شوند | استقرارپذیری مستقل را برگردان یا ادغامشان کن |
| Shared database | دو سرویس روی یک جدول مینویسند | یک مالک؛ بقیه از API یا event استفاده کنند |
| Chatty services | یک صفحه ۴۰ فراخوانی داخلی میسازد | API درشتتر، ترکیب، دادهٔ خواندنی تکثیرشده |
| Nanoservices | سرویس برای هر تابع؛ چسب بیشتر از منطق | ادغام بر اساس انسجام و الگوی تغییر |
| Entity services | CustomerService و OrderService بهشکل CRUD روی جدول | برش بر اساس قابلیت (Checkout، Billing)، نه اسم |
| Microservice envy | انتخاب میکروسرویس از سر مُد | اول monolith؛ حق بیمه را فقط وقتی پیچیدگی بخواهد بپرداز |
چرا وجود دارد
یک واحد استقرار (deployable) یک قوت بزرگ و یک ضعف بزرگ دارد. قوتش: همهچیز فراخوانی تابع است و یک تراکنش دیتابیس. ضعفش: همهچیز با هم منتشر میشود. وقتی پنجاه توسعهدهنده یک deployable مشترک دارند، انتشار هفتگی مذاکره میشود، باگ گزارشگیری جلوی رفع مشکل checkout را میگیرد، و بخشی که ۴۰ سرور لازم دارد همراه بخشی که یک سرور کافیاش است scale میشود. Lewis و Fowler همین سرخوردگی را مینویسند: "Change cycles are tied together - a change made to a small part of the application, requires the entire monolith to be rebuilt and deployed." پاسخ میکروسرویس یک حرکت است: مرز ماژول را مرز پردازه کن تا هر بخش جداگانه تغییر کند، مستقر شود و scale شود.
| یک deployable بماند (monolith یا modular monolith) | شکستن به میکروسرویسها |
|---|---|
| فراخوانی تابع: نانوثانیه، هیچوقت «نیمهکاره» شکست نمیخورد | فراخوانی شبکه: میلیثانیه، timeout، شکست در میانه |
| یک تراکنش ACID بین ماژولها | Saga، eventual consistency، جبران (compensation) |
| یک pipeline، یک runtime برای patch | یک pipeline و runtime برای هر سرویس |
| مرزها با انضباط و تست حفظ میشوند | مرزها را شبکه حفظ میکند (دور زدنش سخت است) |
| همه با هم scale میشوند | هر قابلیت جدا scale میشود |
| با هم منتشر میشوند | مستقل منتشر میشوند (اگر برایش طراحی شده باشد) |
| مناسب: یک یا چند تیم، دامنهٔ جوان | مناسب: تیمهای زیاد، دامنهٔ پایدار، تفاوت واقعی در مقیاس |
تمثیلی که در این صفحه تکرار میشود: آشپزخانهٔ رستوران در برابر فودکورت. رستوران یک آشپزخانه، یک منو و یک سرآشپز دارد: غذاها کاملاً هماهنگاند، اما عوض کردن منو یعنی متوقف کردن کل آشپزخانه، و اگر سرخکن خراب شود هیچکس سیبزمینی نمیگیرد. فودکورت غرفههای مستقل دارد: هر غرفه اجاق، یخچال و کارکنان خودش را دارد (دادهٔ خودش)، منویش را بیاجازهٔ کسی عوض میکند و اگر دیر باز کند بقیه بسته نمیشوند. بهایش: خدمات مشترک لازم است (نظافت، پرداخت، تابلو)، مشتریای که پیتزا و سوشی میخواهد به دو غرفه میرود و ممکن است یکی دیرتر برسد، و اگر همهٔ غرفهها یک یخچال مشترک داشته باشند، در واقع رستورانی هستید که ادای فودکورت را درمیآورد. در هر بخش به همین فودکورت برمیگردیم.
سه بدفهمی رایج، از همین اول
- «میکروسرویس یعنی سرویس کوچک.» اسم گمراه میکند. Lewis و Fowler اندازههایی از یک تیم two-pizza برای هر سرویس تا یک نفر برای هر سرویس دیدهاند و میگویند این اسم "does lead to an unfortunate focus on the size of service". آزمون، استقرارپذیری مستقل و مالکیت است، نه تعداد خط کد.
- «میکروسرویس سیستم را سادهتر میکند.» هر تکه سادهتر میشود و کل سختتر. Fowler: "If the components do not compose cleanly, then all you are doing is shifting complexity from inside a component to the connections between components."
- «میکروسرویس یعنی راه scale کردن.» یک monolith بیحالت (stateless) پشت load balancer بهصورت افقی scale میشود؛ همان مقاله هم همین را میگوید. میکروسرویس سازمان و بار نامتوازن را scale میکند؛ یک درخواست تکی را سریعتر نمیکند (کندترش میکند).
از کجا آمده
ریشهها. Lewis و Fowler ادعای نوآوری ندارند: "its roots go back at least to the design principles of Unix". معماری سرویسگرا (SOA) در دههٔ ۲۰۰۰ همین هدف را داشت؛ تفاوتی که مقالهٔ ۲۰۱۴ رویش تأکید میکند کنار گذاشتن Enterprise Service Bus سنگین (ESB) و حاکمیت متمرکز است (SOA را ببینید). به گفتهٔ همان مقاله Netflix سبکش را "fine-grained SOA" مینامید.
ونیز، ۲۰۱۱ و ۲۰۱۲. پانویس ۱ مقاله: "The term “microservice” was discussed at a workshop of software architects near Venice in May, 2011" و "In May 2012, the same group decided on “microservices” as the most appropriate name." James Lewis این ایدهها را مارس ۲۰۱۲ در کنفرانس 33rd Degree در کراکوف ارائه کرد.
Lewis و Fowler، مارس ۲۰۱۴. مقالهٔ Microservices: a definition of this new architectural term (بخشبهبخش، از ۱۰ تا ۲۵ مارس ۲۰۱۴) نُه ویژگیای را فهرست کرد که این فصل روی آنها ساخته شده است.
هشدارها، ۲۰۱۴ و ۲۰۱۵. نوشتههای Fowler یعنی Microservice Prerequisites (۲۸ اوت ۲۰۱۴)، Microservice Premium (۱۳ مه ۲۰۱۵)، Monolith First (۳ ژوئن ۲۰۱۵) و Microservice Trade-Offs (۱ ژوئیهٔ ۲۰۱۵) تعریف را به یک تصمیم تبدیل کردند. Testing Strategies in a Microservice Architecture از Toby Clemson (۱۸ نوامبر ۲۰۱۴) واژگان تست را داد. کتاب Building Microservices از Sam Newman (ویراست اول در ۲۰۱۴ نوشته و اوایل ۲۰۱۵ منتشر شد، طبق صفحهٔ کتابش) مرجع شد؛ ویراست دوم بازنویسی کامل است با فصلهایی دربارهٔ workflow، استقرار روی Kubernetes، تست با consumer-driven contract، observability و تیمهای stream-aligned.
در مقیاس بزرگ. کتابخانهٔ Hystrix از Netflix (که طبق README اکنون در حالت نگهداری است) timeout، bulkhead، circuit breaker و fallback را بستهبندی کرد. قاعدهٔ تیم two-pizza در Amazon اندازهٔ تیم را شکل داد. Uber در Introducing Domain-Oriented Microservice Architecture (Adam Gluck، ۲۳ ژوئیهٔ ۲۰۲۰) گزارش میدهد (بهروایت ابزار fetch ما) حدود 2,200 میکروسرویس حیاتی دارد و آنها را در 70 دامنه پشت gateway گروهبندی کرده است.
اصلاح مسیر، ۲۰۲۳. تیم Prime Video شرح داد که یک ابزار پایش صوت و تصویر را از طراحی توزیعشدهٔ serverless به یک پردازهٔ واحد برده و هزینه را ۹۰٪ کم کرده است (گزارش InfoQ، مه ۲۰۲۳؛ آدرس پست اصلی اکنون به جای دیگری redirect میشود). مقالهٔ HotOS 2023 گوگل با عنوان Towards Modern Development of Cloud Applications استدلال کرد که "microservices conflate logical boundaries (how code is written) with physical boundaries (how code is deployed)." هیچکدام نمیگویند «هرگز میکروسرویس نسازید»؛ هر دو میگویند هزینهٔ توزیعی را که لازم ندارید نپردازید.
دانهبندی، ۲۰۲۱. کتاب Software Architecture: The Hard Parts از Ford، Richards، Sadalage و Dehghani (فصل ۷، نسخهٔ رایگان Thoughtworks) برای نیروهایی که سرویس را از هم جدا میکنند و دوباره کنار هم میگذارند اسم گذاشت.
Year Event What it changed
1 2011-12 Venice workshop names "microservices" A word for a style already in use
2 2014-03 Lewis & Fowler: nine characteristics A shared definition
3 2014-08 Fowler: Microservice Prerequisites "Not without CD, monitoring, provisioning"
4 2014-11 Clemson: testing strategies Component and contract tests
5 2015 Newman: Building Microservices (1st ed.) The practitioner's book
6 2015-05 Fowler: Microservice Premium "Only above a complexity threshold"
7 2015-06 Fowler: Monolith First Start modular, split later
8 2020-07 Uber: DOMA, ~2,200 services into 70 domains Group services; gateways per domain
9 2021-10 Hard Parts (granularity chapter) Integrators vs disintegrators
10 2023 Prime Video (90% cheaper as one process); Distribution is a cost to justify
Google HotOS paper (logical vs physical)مفهومها، یکییکی
هر بلوک همین ترتیب را دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، یک توالی، سناریوهای واقعی، اینکه هر فناوری چطور فراهمش میکند، و نحوهٔ بهکار بستن.
معماری میکروسرویس (تعریف) حیاتی
به زبان ساده: یک برنامه که بهشکل چند برنامهٔ جدا ساخته شده؛ هر کدام یک کار کسبوکاری انجام میدهد، مال یک تیم است، دادهٔ خودش را دارد و جداگانه منتشر میشود.
بدفهمی رایج: «چون container داکر داریم، میکروسرویس داریم.» container فقط قالب بستهبندی است. ده container که یک دیتابیس مشترک دارند و باید با هم منتشر شوند، یک برنامهاند که روی ده پردازه پخش شدهاند: یک distributed monolith.
تعریف: Lewis و Fowler: "a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery." الگوی Richardson در microservices.io: "Design an architecture that structures the application as a set of two or more independently deployable, loosely coupled, components, a.k.a. services." ویراست دوم Newman (بر اساس فهرست فصلها و خلاصهٔ عمومی کتاب؛ خود فصل ۱ را نتوانستیم بخوانیم) تعریف را روی استقرارپذیری مستقل، مدلسازی حول دامنهٔ کسبوکار و پنهانسازی اطلاعات (information hiding) بنا میکند.
Request: "place order for 2 x sku-1" Where it runs
1 POST /orders -> API gateway edge
2 gateway -> Orders service orders process, orders_db
3 Orders -> GET /products/sku-1 -> Catalog catalog process, catalog_db
4 Orders -> POST /charges -> Billing billing process (Laravel), billing_db
5 Orders commits order + outbox row orders_db only
6 relay -> bus -> Notifications sends the email notifications process, laterسناریوی واقعی: فروشگاه آنلاینی که checkout هر روز، کاتالوگ هر هفته و صدور صورتحساب هر فصل عوض میشود و سه تیم مالکشاناند؛ بانکی که مجوز کارت باید مستقل از تولید صورتحساب scale شود و بالا بماند؛ شرکت تاکسی اینترنتی با هزاران مهندس (حدود 2,200 سرویس Uber).
چه چیزی فراهمش میکند:
| دغدغه | فراهمکنندهٔ رایج |
|---|---|
| پردازه و بستهبندی | Containerها (imageهای Docker/OCI)، یک image برای هر سرویس |
| زمانبندی، scale، خودترمیمی | Deploymentهای Kubernetes، ECS، Nomad |
| فراخوانی سرویس به سرویس | HTTP/JSON، gRPC (grpc-go)، پیامرسانی (RabbitMQ، Kafka) |
| لبه | API gateway / BFF |
| پیدا کردن نمونهها | Service discovery: DNS، Kubernetes Services، Consul |
| Go | net/http، chi، grpc-go، OpenTelemetry Go |
| Laravel | Octane (workerهای ماندگار)، HTTP client، توکنهای Sanctum، صفها |
نحوهٔ استفاده: تعریف را چکلیست کنید: پردازهٔ جدا، دادهٔ مالکیتدار، pipeline خودش، مرزی به شکل کسبوکار، یک تیم مالک. اگر یکی تیک نخورد، چیز دیگری دارید؛ شاید هم خوب باشد، اما صادقانه اسمش را بگذارید.
نُه ویژگی حیاتی
به زبان ساده: نُه شباهت خانوادگی. Lewis و Fowler میگویند "not all microservice architectures have all the characteristics, but we do expect that most microservice architectures exhibit most characteristics."
بدفهمی رایج: «این نُه تا قانوناند و باید رعایتشان کرد.» نویسندهها برعکسش را نوشتهاند: "we are not laying down some definition to conform to." آنها را ابزار تشخیص بدانید: سیستم شما کدام را ندارد و نداشتنش چه هزینهای دارد؟
تصویر نُه ویژگی را دور خاصیتی که همه به آن خدمت میکنند، یعنی استقرارپذیری مستقل، گروهبندی کرده و بهایی را که میپردازید زیرش گذاشته است.
| # | ویژگی | آنچه Lewis و Fowler میگویند (نقلقول) | معنایش در عمل |
|---|---|---|---|
| 1 | Componentization via services | "a component is a unit of software that is independently replaceable and upgradeable" | سرویس مؤلفهای بیرون از پردازه است با رابط منتشرشدهٔ صریح و راه دور |
| 2 | Organized around business capabilities | "splitting up into services organized around business capability" | تیمهای چندمهارتی؛ قانون Conway را ببینید |
| 3 | Products not projects | "a team should own a product over its full lifetime" | «You build, you run it» (Amazon)؛ کشیک برای سرویس خودت |
| 4 | Smart endpoints and dumb pipes | "they own their own domain logic and act more as filters in the classical Unix sense" | ESB با قواعد کسبوکار نداریم؛ HTTP و یک broker ساده |
| 5 | Decentralized governance | "We prefer using the right tool for the job" | Go برای Catalog، Laravel برای Billing؛ استانداردها از کد کارکرده |
| 6 | Decentralized data management | "Microservices prefer letting each service manage its own database" | database per service، Polyglot Persistence، eventual consistency |
| 7 | Infrastructure automation | "we run lots of automated tests. Promotion of working software 'up' the pipeline means we automate deployment" | CI/CD برای هر سرویس، زیرساخت بهشکل کد |
| 8 | Design for failure | "Any service call could fail due to unavailability of the supplier" | timeout، circuit breaker، bulkhead، پایش، تست آشوب |
| 9 | Evolutionary design | "If you find yourself repeatedly changing two services together, that's a sign that they should be merged." | مرزها جابهجا میشوند؛ سرویسها جایگزینپذیرند |
Characteristic missing Symptom you will see
1 componentization "we deploy the shared jar to all services"
2 business capabilities a feature needs the UI, API and DB teams
3 products "the project ended; ops owns it now"
4 smart endpoints business rules inside the broker/ESB config
5 decentralized governance architecture board approves every library
6 decentralized data two services UPDATE the same table
7 automation "release night" for 20 services
8 design for failure one slow dependency hangs every thread
9 evolutionary design services nobody dares to merge or deleteسناریوی واقعی: تیمی «میکروسرویسهایش» را ممیزی میکند: ویژگیهای ۱، ۵ و ۷ هست؛ ۶ نیست (یک PostgreSQL مشترک)، ۸ نیست (timeout ندارد). ممیزی قطعیهایش را توضیح میدهد (یک query کند همه را قفل میکند) و قطارهای انتشارش را هم (تغییر schema همهٔ تیمها را میخواهد). ترتیب اصلاح هم از همین درمیآید: اول مالکیت داده، بعد timeoutها.
نحوهٔ استفاده: هر فصل یک بار به هر سرویس برای این نُه ویژگی از ۰ تا ۲ نمره بدهید؛ کمترین نمرهها کار معماری بعدی شماست.
استقرارپذیری مستقل (آزمون واقعی) حیاتی
به زبان ساده: آیا این تیم میتواند همین امروز این سرویس را به production ببرد، بدون اجازه از تیم دیگر و بدون اینکه کس دیگری همزمان منتشر کند؟
بدفهمی رایج: «repository جدا یعنی استقرار مستقل.» میشود بیست repository داشت و باز انتشار هماهنگ لازم داشت؛ بهخاطر دیتابیس مشترک، کتابخانهٔ مشترک با typeهای دامنه، یا یک تغییر شکنندهٔ API.
تعریف: Lewis و Fowler: "One main reason for using services as components (rather than libraries) is that services are independently deployable." حدش را هم میگویند: "some changes will change service interfaces resulting in some coordination, but the aim of a good microservice architecture is to minimize these through cohesive service boundaries and evolution mechanisms in the service contracts." Richardson نیروی متناظر را اینطور مینویسد: "Team autonomy - a team needs to be able to develop, test and deploy their software independently of other teams".
Billing adds a field "tax_cents" to its charge response
1 Billing deploys v2 (adds field; old fields unchanged) consumers keep working (tolerant reader)
2 Orders deploys later, starts reading tax_cents no lock-step
--- versus a lock-step change ---
1 Billing renames amount_cents -> amount Orders breaks immediately
2 "release both on Tuesday at 22:00" distributed monolith behaviourسناریوی واقعی: متریک deployment frequency در DORA ("The number of deployments over a given period or the time between deployments") ابزار اندازهگیری است؛ اگر تعداد استقرارهای Billing را تقویم انتشار Orders محدود کند، این سرویسها مستقل نیستند. نشانههای دیگر: کتابخانهٔ مشترک common-models که هر sprint در همهٔ سرویسها بالا برده میشود؛ محیط یکپارچهسازیای که باید نسخهٔ جفتشدهٔ همهٔ سرویسها را نگه دارد.
چه چیزی فراهمش میکند:
| سازوکار | مثال |
|---|---|
| تغییرهای API سازگار با عقب | فیلد اضافه کن، هرگز تغییر نام نده؛ Tolerant Reader |
| contract testهای مصرفکنندهمحور در pipeline تأمینکننده | Pact، Spring Cloud Contract، contract test Go همین صفحه |
| دادهٔ مالکیتدار | هیچ سرویس دیگری billing_db را نمیخواند |
| یک pipeline برای هر سرویس | فقط آنچه عوض شده build، تست و مستقر میشود |
| feature flag، expand-and-contract | کد را خاموش منتشر کن، بعداً روشن کن |
| راهبردهای استقرار | Rolling update، blue/green و canary |
نحوهٔ استفاده: به تعریف «انجامشده» (definition of done) این قاعده را اضافه کنید: «این تغییر را میشود تنها مستقر کرد». اگر نمیشود، pull request باید بگوید چرا و کدام گامهای expand-and-contract در ادامه میآیند.
دانهبندی: نیروهای تجزیه و تجمیع حیاتی
به زبان ساده: هم دلیل خوب برای شکستن سرویس هست و هم دلیل خوب برای کنار هم نگه داشتن؛ اندازهٔ درست جایی است که این دو تعادل پیدا میکنند.
بدفهمی رایج: «کوچکتر همیشه بهتر است.» Ford، Richards و همکاران: "One common mistake many development teams make is focusing too much on granularity disintegrators while ignoring granularity integrators."
تعریف: کتاب Software Architecture: The Hard Parts، فصل ۷. نیروهای تجزیه (granularity disintegrators) به این سؤال جواب میدهند: "When should I consider breaking apart a service into smaller parts?"؛ نیروهای تجمیع (granularity integrators) به این یکی: "When should I consider putting services back together?" دو جدول خلاصهٔ کتاب:
| نیروی تجزیه (Disintegrator) | سؤالی که کتاب میپرسد | دلیل در جدول 7-2 |
|---|---|---|
| Service scope and function | Is the service doing too many unrelated things? | Single-purpose services with tight cohesion |
| Code volatility | Are changes isolated to only one part of the service? | Agility (reduced testing scope and deployment risk) |
| Scalability and throughput | Do parts of the service need to scale differently? | Lower costs and faster responsiveness |
| Fault tolerance | Are there errors that cause critical functions to fail within the service? | Better overall uptime |
| Security | Do some parts of the service need higher security levels than others? | Better security access control to certain functions |
| Extensibility | Is the service always expanding to add new contexts? | Agility (ease of adding new functionality) |
| نیروی تجمیع (Integrator) | دلیل در جدول 7-3 |
|---|---|
| Database transactions | Data integrity and consistency |
| Workflow (and choreography) | Fault tolerance, performance, and reliability |
| Shared code | Maintainability |
| Data relationships | Data integrity and correctness |
Notifications: SMS + email + postal letter in one service?
1 scope: one job ("notify the customer") -> keep (integrator wins)
2 volatility: postal letter rules change monthly -> consider splitting letter out
3 scalability: email 1,000/min, letters 50/day -> split email out?
4 workflow: one notification fans out to all three -> splitting adds calls
Decision: one Notifications service; revisit if letter volatility persistsسناریوی واقعی: مثال خود کتاب یک Notification Service است که SMS، ایمیل و نامهٔ پستی را میفرستد؛ مثال دیگرش سرویس پرداختی است که شکستنش بر اساس روش پرداخت توسعهپذیری را بهتر میکند اما سفارشهایی را که با چند روش پرداخت میشوند کند میکند. در پلتفرم ما Catalog و قیمتگذاری کنار هم ماندند (قیمت در هر درخواست همراه محصول خوانده میشود؛ نیروی تجمیع workflow)، اما Billing جدا شد (نیروی تجزیهٔ امنیت: دامنهٔ PCI؛ و ناپایداری کد: درگاههای پرداخت عوض میشوند).
نحوهٔ استفاده: trade-off را برای مالک محصول به شکل جمله بنویسید، به همان شکلی که کتاب پیشنهاد میکند: "We want to break apart our service to isolate frequent code changes, but in doing so we won't be able to maintain a database transaction. Which is more important...?" روش دقیق کشیدن مرزها در Service Boundaries و Bounded Context است.
ساختار تیم: Conway، two-pizza، stream-aligned مهم
به زبان ساده: سرویسهایتان از روی چارت سازمانیتان کپی میشوند؛ پس چارتی را بکشید که میخواهید سرویسها شبیهش باشند.
بدفهمی رایج: «معماری تصمیم فنی است و تیمها تصمیم منابع انسانی.» قانون Conway (Conway's Law) به نقل Lewis و Fowler: "Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure." شکستن سرویس بدون شکستن مالکیت، سرویسهایی میسازد که همه ویرایششان میکنند.
تعریف:
| ایده | منبع (نقلقول) | کاربرد |
|---|---|---|
| تیم two-pizza | whitepaper از AWS به نقل از Bezos: "We try to create teams that are no larger than can be fed by two pizzas" | سقف اندازهٔ تیم مالک سرویس (Lewis و Fowler: "no more than a dozen people") |
| Inverse Conway Maneuver | Fowler در Microservice Premium: سازمانهایی که "deliberately split themselves into small, loosely coupled groups in order to push the software into a similar modular structure" | اول تیمها را عوض کن، کد دنبالش میآید |
| تیم stream-aligned | Team Topologies: "aligned to a flow of work from (usually) a segment of the business domain" | مالک یک یا چند سرویس از سر تا ته |
| Platform team | Team Topologies: فراهمکنندهٔ "a compelling internal product to accelerate delivery by Stream-aligned teams" | مالک «جادهٔ هموار»: CI/CD، observability، mesh |
| تیمهای enabling و complicated-subsystem | مفاهیم کلیدی Team Topologies | مربیگری؛ مؤلفههای تخصصی (مثلاً موتور قیمتگذاری) |
Org Services you will get
1 UI team, API team, DB team three layers that every feature crosses
2 Checkout team, Catalog team, Checkout, Catalog, Billing services
Billing team + platform team plus a shared platform (CI, tracing, mesh)سناریوی واقعی: پست DOMA از Uber شرح میدهد که تیمها داخل سرویسهای همدیگر کد مینوشتند و مدل دادهٔ همدیگر را تغییر میدادند (نقل به مضمون؛ پست را از طریق ابزار fetch خواندیم، منابع را ببینید)؛ پاسخ DOMA گروهبندی سرویسها در دامنهها پشت gateway بود. تیمهای two-pizza در Amazon مالک سرویساند و اجرایش میکنند («you build, you run it» به نقل Lewis و Fowler).
نحوهٔ استفاده: هر سرویس دقیقاً یک تیم مالک دارد (در CODEOWNERS و کاتالوگ سرویسها نوشته شود)؛ یک تیم میتواند مالک چند سرویس باشد. اگر سرویسی دو مالک دارد، یا تیمها را ادغام کنید یا سرویس را بشکنید. جزئیات: Service Boundaries.
حق بیمهٔ میکروسرویس و پیشنیازها حیاتی
به زبان ساده: میکروسرویس هر روز هزینهٔ اضافه دارد؛ فقط وقتی بپردازیدش که سیستم برای یک deployable زیادی پیچیده شده، و فقط بعد از اینکه بتوانید سریع تأمین (provision)، پایش و مستقر کنید.
بدفهمی رایج: «پایش و CI را بعداً که سرویسها ساخته شدند اضافه میکنیم.» Fowler: "if you don't have certain baseline competencies, you shouldn't consider using the microservice style."
تعریف: در Microservice Premium: "When you use microservices you have to work on automated deployment, monitoring, dealing with failure, eventual consistency, and other factors that a distributed system introduces." رهنمودش: "don't even consider microservices unless you have a system that's too complex to manage as a monolith." در Monolith First: "Almost all the successful microservice stories have started with a monolith that got too big and was broken up". پیشنیازها (prerequisites، Fowler ۲۰۱۴): تأمین سریع، پایش پایه، استقرار سریع برنامه و فرهنگ DevOps؛ و پس از چند سرویس اول، ردگیری تراکنشهای کسبوکاری بین سرویسها و continuous delivery کامل.
| پیشنیاز | حداقل | نمونهٔ ابزار |
|---|---|---|
| Rapid provisioning | "fire up a new server in a matter of hours" (Fowler) | Terraform، namespaceهای Kubernetes، یک قالب سرویس |
| Basic monitoring | خطاها، دسترسپذیری و متریکهای کسبوکار ("a drop in orders") | Prometheus، Grafana، هشدار روی SLO |
| Rapid deployment | pipelineای "that can execute in no more than a couple of hours" | GitHub Actions، GitLab CI، Argo CD |
| فرهنگ DevOps | توسعهدهندهها در پاسخ به حادثه و تحلیل ریشه | نوبت کشیک برای هر سرویس |
| Distributed tracing (بعد از چند سرویس) | "trace business transactions through multiple services" | OpenTelemetry، Jaeger، Tempo |
| یک پلتفرم | جادهٔ هموار برای سرویسهای تازه | قالب سرویس، chassis، mesh |
Premium over time (illustrative)
1 month 1 monolith: 1 pipeline, 1 dashboard productive at once
2 month 1 microservices: 4 pipelines, tracing, mesh weeks of platform work first
3 year 2 monolith with 60 devs: merge queue, risky premium now worth paying
4 year 2 microservices: teams ship daily if the prerequisites existسناریوی واقعی: Fowler عواملی را که حق بیمه را توجیه میکنند نام میبرد: "dealing with large teams, multi-tenancy, supporting many user interaction models, allowing different business functions to evolve independently, and scaling"، و بیش از همه "sheer size". ابزار پایش Prime Video روی دیگر سکه است: برای یک تیم با یک pipeline پرداده، توزیع فقط هزینه اضافه کرد (رفتوبرگشت S3 برای هر فریم، انتقالهای حالت زیاد در Step Functions) بیآنکه سودی داشته باشد.
نحوهٔ استفاده: پیش از اولین جداسازی، پلتفرم باید با یک فرمان یک سرویس تازه بسازد که CI/CD، endpointهای health، لاگ، متریک و trace در آن سیمکشی شده باشد. روش تصمیم: Monolith vs Microservices vs Modular Monolith.
دغدغههای مشترک: chassis، sidecar، service mesh مهم
به زبان ساده: هر سرویس همان لولهکشی را لازم دارد (auth، لاگ، trace، متریک، health، config، secret)؛ یک بار بسازیدش و دوباره استفاده کنید، یا بهشکل کتابخانه درون سرویس یا بهشکل proxy کنارش.
بدفهمی رایج: «هر تیم باید لولهکشی خودش را بنویسد؛ حاکمیت غیرمتمرکز همین است.» حاکمیت غیرمتمرکز دربارهٔ انتخاب ابزار است؛ بیست بار پیادهسازی اعتبارسنجی توکن راه پیدایش حفرههای امنیتی است. Lewis و Fowler ابزار مشترک را "Make it easy to do the right thing" مینامند.
تعریف: microservices.io دغدغههای مشترکی (cross-cutting concerns) را که یک microservice chassis بر عهده میگیرد اینطور فهرست میکند: "Security"، "Externalized configuration"، "Logging"، "Health check"، "Metrics" و "Distributed tracing". پاسخ بیرون از پردازه sidecar است: "Implement cross-cutting concerns in a sidecar process or container that runs alongside the service instance." یک service mesh sidecar (یا proxy روی node) را به همهٔ ترافیک اعمال میکند: "Use a service mesh that mediates all communication in and out of each service." در Istio، data plane از "a set of intelligent proxies (Envoy) deployed as sidecars" تشکیل شده و control plane "manages and configures the proxies to route traffic".
| دغدغه | درون پردازه (کتابخانهٔ chassis) | بیرون پردازه (sidecar / mesh) |
|---|---|---|
| auth سرویس به سرویس | middleware در Go که JWT را بررسی میکند؛ auth:sanctum در Laravel | mTLS بین sidecarها، هویت برای هر workload |
| لاگ | JSON با log/slog و trace_id؛ Context در Laravel | DaemonSet ارسال لاگ (Fluent Bit) |
| Tracing | SDK مربوط به OpenTelemetry، otelhttp | spanهای proxy (Envoy)؛ برنامه همچنان باید headerها را منتقل کند |
| متریک | متریکهای OpenTelemetry، کلاینت Prometheus | متریکهای درخواست در proxy (golden signals) |
| retry، timeout، breaker | در کد کلاینت (پکیج resilience همین صفحه) | سیاست retry/timeout/outlier-detection در mesh |
| Config | متغیر محیطی، 12-factor | ConfigMap، سرویس feature flag |
| Secrets | خواندن از فایل/env هنگام شروع | انبار secret (Vault، Kubernetes Secrets، KMS ابری) که پلتفرم mount میکند |
| Health | /livez، /readyz؛ /up در Laravel | probeهایی که kubelet اجرا میکند |
One call, with a mesh
1 orders process -> localhost:15001 (sidecar) app speaks plain HTTP
2 sidecar -> mTLS -> catalog's sidecar identity, encryption, retry policy, metrics
3 catalog sidecar -> catalog process app still receives traceparent
Without a mesh, steps 1-3 are a direct HTTP call and the chassis does the work.سناریوی واقعی: شرکتی با سرویسهای Go، PHP و Java یک mesh میآورد تا بدون سه کتابخانه، mTLS و متریک یکدست بگیرد؛ تیم کوچکی با چهار سرویس Go یک پکیج chassis نگه میدارد (مثل internal/platform پایین) و mesh ندارد.
نحوهٔ استفاده: با chassis شروع کنید (ارزان و قابل اشکالزدایی)؛ وقتی زبانهای زیاد دارید، mTLS همهجا لازم است، یا یک platform team برای ادارهاش دارید، mesh اضافه کنید. جزئیات در API Gateway, BFF & Service Mesh و Service Mesh & the Sidecar Pattern.
داده: database per service (خلاصه) حیاتی
به زبان ساده: هر سرویس دادهاش را خصوصی نگه میدارد؛ بقیه از API میپرسند یا به eventها گوش میدهند.
بدفهمی رایج: «database per service یعنی یک سرور دیتابیس برای هر سرویس.» microservices.io سه گزینه با همان حریم خصوصی میشمارد: "Private-tables-per-service"، "Schema-per-service" و "Database-server-per-service" و میگوید دو تای اول "have the lowest overhead".
تعریف: "Keep each microservice’s persistent data private to that service and accessible only via its API." پیامدش: join بین سرویسها و تراکنش ACID بین سرویسها نداریم. Lewis و Fowler: "Distributed transactions are notoriously difficult to implement and as a consequence microservice architectures emphasize transactionless coordination between services, with explicit recognition that consistency may only be eventual consistency and problems are dealt with by compensating operations." ابزارها: saga ("A saga is a reliably coordinated sequence of local transactions.")، transactional outbox، مصرفکنندهٔ idempotent، و مدلهای خواندنی CQRS برای queryهایی که چند سرویس را در بر میگیرند. هر سرویس میتواند انبار دادهٔ خودش را انتخاب کند: Polyglot Persistence. مثال این صفحه پرداخت را همزمان انجام میدهد (Orders، Billing را صدا میزند و منتظر میماند)؛ گزینهٔ ناهمزمان، که در آن Billing به OrderPlaced واکنش نشان میدهد، یک saga است:
Checkout as a saga (orchestrated by Orders)
1 Orders: INSERT order (PENDING) + outbox OrderPlaced local tx in orders_db
2 Billing: capture payment -> PaymentCaptured local tx in billing_db
3 Orders: mark order CONFIRMED local tx
Failure at 2: Billing emits PaymentFailed -> Orders marks CANCELLED (compensation)نحوهٔ استفاده: یک مالک برای هر جدول، که با credential دیتابیس اعمال شود (نقش هر سرویس فقط schema خودش را میبیند؛ SQL را در سازوکار ببینید). گزینههای brownfield، مهاجرت از دیتابیس مشترک و گزارشگیری: Data Ownership in Microservices و Data Patterns.
ارتباط: sync و async (خلاصه) مهم
به زبان ساده: فقط وقتی جواب را همین حالا لازم دارید همزمان (sync) صدا بزنید؛ وقتی بقیه فقط باید باخبر شوند، ناهمزمان (async) خبرشان کنید.
بدفهمی رایج: «کافی است فراخوانی متدها را به فراخوانی HTTP تبدیل کنیم.» Lewis و Fowler: "A naive conversion from in-memory method calls to RPC leads to chatty communications which don't perform well." و: "Any time you have a number of synchronous calls between services you will encounter the multiplicative effect of downtime."
تعریف: دو سبک غالب طبق مقالهٔ ۲۰۱۴: "HTTP request-response with resource API's and lightweight messaging". در مثال ما Orders بهصورت sync از Catalog میپرسد (برای پذیرفتن سفارش قیمت لازم است) و Notifications را async باخبر میکند (مشتری میتواند ایمیل را یک ثانیه بعد بگیرد). قاعدهٔ Guardian به نقل مقاله: "one synchronous call per user request".
| نیاز | سبک | مثال در پلتفرم سفارش |
|---|---|---|
| برای ادامه جواب لازم است | sync request-response (HTTP/JSON، gRPC) | Orders قیمت را از Catalog میخواند |
| بقیه باید واکنش نشان دهند، فراخواننده لازم نیست صبر کند | event ناهمزمان (RabbitMQ، Kafka) | OrderPlaced.v1 به Notifications |
| فرایند کسبوکاری بلند و چندمرحلهای | saga روی پیامها | سفارش، پرداخت، ارسال |
| خواندن زیاد از دادهٔ سرویس دیگر | مدل خواندنی تکثیرشده با event | Orders یک snapshot از قیمت نگه میدارد |
قرارداد، idempotency key، retry و انتخاب پروتکل در Service Communication آموزش داده میشود؛ request-reply روی broker در Request-Reply.
تابآوری: طراحی برای شکست (خلاصه) حیاتی
به زبان ساده: هر فراخوانی راه دور یک ضربالاجل، یک retry محدود، یک breaker که صدا زدن وابستگی مرده را متوقف کند، و برنامهای برای آنچه کاربر میبیند لازم دارد.
بدفهمی رایج: «هر سرویس ما 99.99% دسترسپذیری دارد، پس کل سیستم هم.» ویکی Hystrix از Netflix این حساب را برای برنامهای با 30 وابستگی که هر کدام 99.99% است انجام میدهد: 99.7% uptime، یعنی "2+ hours downtime/month even if all dependencies have excellent uptime."
تعریف: الگوهای پایداری که Lewis و Fowler از کتاب Release It! نوشتهٔ Nygard نقل میکنند: Circuit Breaker، Bulkhead و Timeout. نوشتهٔ CircuitBreaker از Fowler: "You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all." Hystrix به اینها fallback و جداسازی را اضافه میکند: "such as bulkhead, swimlane, and circuit breaker patterns".
Catalog dies; Orders' client: 300 ms per try, 2 tries, breaker threshold 5, cooldown 10 s
1 req1: try1 refused, try2 refused failures=2 503 (6 ms)
2 req2: try1, try2 refused failures=4 503
3 req3: try1 refused -> failures=5 -> OPEN 503 (13 ms)
4 req4: breaker open, no network call 503 in 0.5 ms, Retry-After: 10
5 +10 s: half-open, one trial call success -> CLOSED; failure -> OPEN againاعداد از آزمایشگاه همین صفحه است. هر الگو فصل خودش را دارد: Timeouts, Retries & Jitter، Circuit Breaker، Bulkheads & Graceful Degradation، Cascading Failures، Chaos Engineering.
Observability: لاگ، متریک، trace، correlation ID حیاتی
به زبان ساده: وقتی یک کلیک به پنج سرویس میرسد، یک شناسه لازم دارید که همهجا دنبال کلیک برود، و هر سرویس باید با همان شناسه لاگ بنویسد، بشمارد و زمان بگیرد.
بدفهمی رایج: «لاگ متمرکز کافی است.» لاگ پنج سرویس بدون شناسهٔ مشترک یعنی پنج انبار کاه. پست DOMA از Uber هم همین را میگوید: بدون ابزار درست نمیبینید چه میگذرد و اشکالزدایی سخت میشود (نقل به مضمون).
تعریف: سه سیگنال: لاگ (logs) (رویدادها، JSON ساختیافته)، متریک (metrics) (اعداد تجمیعی: نرخ، خطا، مدت) و trace (traces) (درخت علّی spanهای یک درخواست). انتقال با header استاندارد W3C Trace Context انجام میشود: "traceparent describes the position of the incoming request in its trace graph in a portable, fixed-length format"، مثلاً traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01 (نسخه، trace-id، parent-id، flags). OpenTelemetry یک SDK و پروتکل (OTLP) بیطرف نسبت به فروشنده برای تولید هر سه است؛ در Go، otelhttp.NewHandler و otelhttp.NewTransport spanها را میسازند و منتقل میکنند. یک correlation ID شناسهٔ درخواست در سطح کسبوکار است (اینجا X-Correlation-ID) که آن را هم لاگ میکنید؛ Lewis و Fowler پایش معنایی (semantic monitoring) متریکهای کسبوکار را هم اضافه میکنند ("how many orders per minute are received").
تصویر trace واقعی آزمایشگاه است: یک trace ID در Orders، Catalog و یک ثانیه بعد، از مسیر outbox، در Notifications.
| سیگنال | Go در این صفحه | Laravel در این صفحه | نمونههای backend |
|---|---|---|---|
| Trace | handler و transport از otelhttp، propagator استاندارد W3C | traceparent در Context ذخیره و ارسال میشود | Jaeger، Tempo، Zipkin، APMهای تجاری |
| لاگ | JSON با slog همراه trace_id و correlation_id | Context::add(...) فیلدها را به هر خط لاگ اضافه میکند | Loki، Elasticsearch |
| متریک | meter مربوط به OpenTelemetry یا کلاینت Prometheus | Pulse، exporter برای Prometheus | Prometheus، Mimir |
| Health | /livez، /readyz | /up + listener روی DiagnosingHealth | probeهای Kubernetes |
پرشهای ناهمزمان trace را گم میکنند مگر آن را با خود ببرید: relay در Go، traceparent را در ردیف outbox ذخیره میکند و هنگام انتشار برمیگرداند. عمق بیشتر: Observability، Messaging Observability.
تست: unit، component، contract، end-to-end حیاتی
به زبان ساده: هر سرویس را تنها، سریع و کامل تست کنید؛ توافقهای بین سرویسها را با contract test بسنجید؛ تستهای کند end-to-end را کم نگه دارید.
بدفهمی رایج: «برای تست هر چیزی محیطی کامل با هر ۴۰ سرویس لازم داریم.» microservices.io: "End to end testing (i.e. tests that launch multiple services) is difficult, slow, brittle, and expensive."
تعریف: ارائهٔ Clemson (سایت Fowler، ۲۰۱۴؛ ما فهرست مطالبش را خواندیم) بر اساس تست unit، integration، component، contract و end-to-end مرتب شده است. در خوانش رایج، component test یک سرویس را در انزوا و با همکارانی که test double جایشان نشسته میسنجد، و contract test شکل یک یکپارچگی را. Pact: "Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a "contract"." در قراردادهای مصرفکنندهمحور (consumer-driven contract)، مصرفکننده انتظاراتش را مینویسد و pipeline تأمینکننده اجرایش میکند؛ Pact میگوید "any provider behaviour not used by current consumers is free to change without breaking tests."
| لایه | دامنه | سرعت | در این صفحه |
|---|---|---|---|
| Unit | یک تابع یا کلاس | ms | breaker_test.go |
| Integration | یک adapter در برابر وابستگی واقعی (DB، broker) | s | Testcontainers (نشان داده نشده) |
| Component | یک سرویس، وابستگیها جعلی | s | feature test در Laravel با PaymentProvider mockشده |
| Contract | یک جفت مصرفکننده-تأمینکننده | ms تا s | contract_test.go (Go)، ChargeContractTest.php (Laravel) |
| End-to-end | کل سیستم | دقیقه | فقط چند مسیر smoke، بهعلاوهٔ آزمایشگاه |
Consumer-driven contract flow (Orders -> Catalog)
1 Orders team writes testdata/orders-gets-product.json expectation
2 Orders CI: consumer test decodes the contract response Orders understands it
3 Catalog CI: provider test replays the request on the real handler
4 Catalog renames price_cents -> price provider test fails in Catalog's CI
5 Nothing reached production; no shared environment neededنحوهٔ استفاده: یک هرم تست (test pyramid) برای هر سرویس و یک contract برای هر یکپارچگی. قراردادهای پیامرسانی: Testing Messaging Systems.
استقرار: container، Kubernetes، rolling، blue/green، canary مهم
به زبان ساده: هر سرویس را یک image کنید، بگذارید یک orchestrator چند نسخهاش را اجرا کند، و نسخههای قدیم را تدریجی با جدید عوض کنید، با یک راه برگشت سریع.
بدفهمی رایج: «Kubernetes به ما میکروسرویس میدهد.» صفحهٔ کتاب Newman: دیدن تیمهایی که "flock to Kubernetes in the hope that it would solve all their issues with microservice architectures" او را به فکر انداخت. Kubernetes container اجرا میکند؛ مرزها و مالکیت داده را درست نمیکند.
تعریف:
| راهبرد | تعریف (منبع) | Kubernetes / ابزار |
|---|---|---|
| Rolling update | جایگزینی تدریجی podها؛ پیشفرضها "25% max unavailable, 25% max surge" (مستندات Kubernetes) | Deployment با strategy: RollingUpdate، maxUnavailable، maxSurge |
| Blue/green | "two production environments, as identical as possible"؛ router را عوض کن؛ "rapid way to rollback" (Fowler) | دو Deployment، عوض کردن selector سرویس |
| Canary | "slowly rolling out the change to a small subset of users before rolling it out to the entire infrastructure" (Sato در سایت Fowler) | دو Deployment با وزن؛ mesh یا Argo Rollouts |
| Probeها | "Liveness probes determine when to restart a container"؛ readiness ترافیک را از podهای آمادهنشده قطع میکند (مستندات Kubernetes) | livenessProbe، readinessProbe، startupProbe |
Rolling update of orders 1.4.1 -> 1.4.2, replicas 3, maxUnavailable 0, maxSurge 1
1 start pod 1.4.2 #1 startupProbe until /livez answers
2 readinessProbe /readyz ok Service sends traffic to it
3 stop one 1.4.1 pod: SIGTERM our Serve(): /readyz -> 503, sleep 2 s, Shutdown drains
4 repeat until 3 x 1.4.2 never fewer than 3 ready pods# Orders on Kubernetes: rolling update with zero unavailable pods, and
# probes wired to the endpoints in internal/platform/health.go.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders
labels: { app: orders }
spec:
replicas: 3
selector:
matchLabels: { app: orders }
strategy:
type: RollingUpdate
rollingUpdate: { maxUnavailable: 0, maxSurge: 1 }
template:
metadata:
labels: { app: orders, version: "1.4.2" }
spec:
terminationGracePeriodSeconds: 30
containers:
- name: orders
image: registry.example.com/orders:1.4.2
ports: [{ containerPort: 8080 }]
env:
- { name: CATALOG_URL, value: "http://catalog:8081" }
- { name: NOTIFICATIONS_URL, value: "http://notifications:8082" }
- { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: "http://otel-collector:4318" }
startupProbe:
httpGet: { path: /livez, port: 8080 }
failureThreshold: 30
periodSeconds: 1
livenessProbe:
httpGet: { path: /livez, port: 8080 }
periodSeconds: 10
readinessProbe:
httpGet: { path: /readyz, port: 8080 }
periodSeconds: 2
resources:
requests: { cpu: 100m, memory: 64Mi }
limits: { memory: 256Mi }عمق بیشتر: Containers & Kubernetes. برای اندازهگیری تعداد استقرار (deployment frequency)، پنج متریک DORA عبارتاند از change lead time، deployment frequency، failed deployment recovery time، change fail rate و deployment rework rate؛ DORA میگوید اینها "are best suited for measuring one application or service at a time".
نسخهبندی و سازگاری حیاتی
به زبان ساده: APIها را طوری عوض کنید که فراخوانندههای قدیمی کار کنند؛ اضافه کنید، تغییر نام ندهید؛ فقط وقتی حذف کنید که همهٔ فراخوانندهها مهاجرت کردهاند.
بدفهمی رایج: «هر بار چیزی عوض شد /v2/ بگذار در URL.» Lewis و Fowler: "the preference in the microservice world is to only use versioning as a last resort. We can avoid a lot of versioning by designing services to be as tolerant as possible to changes in their suppliers."
تعریف: Tolerant Reader (Fowler، ۲۰۱۱) بر پایهٔ قانون Postel: "be conservative in what you do, be liberal in what you accept from others." مصرفکنندهها فقط فیلدهایی را که لازم دارند میخوانند و بقیه را نادیده میگیرند؛ تأمینکنندهها تغییر افزایشی میدهند. وقتی تغییر شکننده اجتنابناپذیر است: expand (فیلد یا endpoint تازه را اضافه کن)، مهاجرت مصرفکنندهها (contract testها میگویند چه کسانی)، contract (قدیمی را حذف کن). مقالهٔ HotOS گوگل هزینهٔ شکست این کار را نام میبرد: "C4: It freezes APIs. Once a microservice establishes an API, it becomes hard to change without breaking the other services that consume the API."
| تغییر | امن؟ | چطور |
|---|---|---|
| افزودن فیلد اختیاری به پاسخ | بله | مصرفکنندهٔ tolerant نادیدهاش میگیرد (json.Decoder در Go بهطور پیشفرض فیلد ناشناخته را نادیده میگیرد) |
| افزودن فیلد اختیاری به درخواست با مقدار پیشفرض | بله | تأمینکننده نبودنش را پیشفرض حساب میکند |
| تغییر نام یا حذف فیلد | نه | expand-and-contract؛ مدتی هر دو اسم را بنویس |
| تغییر معنا یا واحد فیلد | نه | فیلد تازه (amount_minor)، هرگز اسم را دوباره استفاده نکن |
| اجباری کردن فیلد اختیاری درخواست | نه | endpoint یا نسخهٔ تازه |
| تغییر schema یک event | بستگی دارد | Message design & schema evolution |
عمق بیشتر: API Versioning & Evolution.
ضدالگوها: distributed monolith و دوستانش حیاتی
به زبان ساده: بیشتر پروژههای میکروسرویس شکستخورده سرویس دارند، اما استقلال ندارند.
بدفهمی رایج: «اگر به سرویس شکسته شده، میکروسرویس است.» مقالهٔ گوگل فهرست میکند چه چیزهایی حتی در سازمانهای خوشاداره خراب میشود: "C1: It hurts performance"، "C2: It hurts correctness"، "C3: It is hard to manage"، "C4: It freezes APIs"، "C5: It slows down application development."
تعریف:
| ضدالگو | تعریف | چطور تشخیصش بدهیم | راهحل |
|---|---|---|---|
| Distributed monolith | سرویسهایی که باید با هم build، تست یا منتشر شوند | قطار انتشار؛ سندهای «ترتیب استقرار» | استقلال را برگردان (قرارداد، دادهٔ مالکیتدار) یا ادغام کن |
| Shared database | چند سرویس روی یک جدول میخوانند و مینویسند | دو سرویس در pg_stat_activity روی یک جدول | یک مالک؛ API یا event؛ مالکیت داده |
| Chatty services | فراخوانیهای ریزدانه برای هر درخواست | traceهایی با دهها span برای یک صفحه | API درشتتر، ترکیب API، مدل خواندنی |
| Nanoservices | سرویسهایی آنقدر کوچک که سربارشان از ارزششان بیشتر است | YAML بیشتر از کد؛ سرویسهایی که همیشه با هم عوض میشوند | ادغام بر اساس انسجام (نیروهای تجمیع) |
| Entity services | یک سرویس برای هر اسم که CRUD انجام میدهد | هر use case پنج entity service را صدا میزند | برش بر اساس قابلیت (Service Boundaries) |
| کتابخانهٔ دامنهٔ مشترک | یک jar/package مشترک با typeهای دامنه | بالا بردن یک کتابخانه همه را دوباره مستقر میکند | فقط کد فنی را به اشتراک بگذار؛ DTOهای کوچک را تکرار کن |
| زنجیرهٔ فراخوانی sync | A، B را صدا میزند، B، C را، C، D را | تأخیر = جمع؛ دسترسپذیری = ضرب | eventهای async، کپی محلی، یک فراخوانی sync در هر درخواست |
| Microservice envy | انتخاب سبک از سر مُد | هیچ دلیل تیمی، مقیاسی یا دامنهای | اول monolith |
Distributed monolith in a trace
1 GET /checkout -> orders -> catalog -> pricing -> tax -> currency 5 sync hops
2 each hop 99.9% available 0.999^5 = 99.5%
3 each hop p99 120 ms p99 adds up, ~600 ms
4 pricing schema change orders, tax, currency redeployنقش چهار سرویس در کنار هم
تصویر همان مثال کامل است. Orders از Catalog میپرسد (sync، محافظتشده) و Billing را صدا میزند (sync، با توکن ماشینی و idempotency key)، سفارش و یک ردیف outbox را در دیتابیس خودش ذخیره میکند و OrderPlaced.v1 را منتشر میکند؛ Notifications آن را با یک inbox (حذف تکراری) مصرف میکند. هیچ فلشی به دیتابیس سرویس دیگری اشاره نمیکند.
| سرویس | مالک | عرضه میکند | صدا میزند | Stack |
|---|---|---|---|---|
| Orders | سفارشها، outbox | POST /orders | Catalog (sync)، Billing (sync)، bus (async) | Go، chi، OpenTelemetry |
| Catalog | محصولات، قیمتها | GET /products/{sku} | هیچ | Go، chi |
| Billing | پرداختها (charges) | POST /api/charges (ability سنکتوم charges:create) | درگاه پرداخت | Laravel 13، Octane، Sanctum |
| Notifications | پیامهای ارسالشده، inbox | مصرف OrderPlaced.v1 | سرویسدهندههای ایمیل/SMS | Go در آزمایشگاه |
سازوکار
کالبد یک سرویس
| بخش | Go (این صفحه) | Laravel (این صفحه) |
|---|---|---|
| Router | chi (chi.NewRouter، chi.URLParam) | routes/api.php |
| پردازهٔ سرور | Server از net/http، ReadHeaderTimeout | Octane روی FrankenPHP (و RoadRunner، Swoole) |
| Health | /livez، /readyz | /up (200 وقتی boot شد) + event DiagnosingHealth |
| خاموشی آرام (graceful shutdown) | signal.NotifyContext، unready، Shutdown | توقف worker در Octane؛ preStop در Kubernetes |
| auth ورودی | middleware برای mTLS یا JWT (نشان داده نشده) | auth:sanctum + abilities:charges:create |
| کلاینت خروجی | http.Client + otelhttp.NewTransport، timeout، retry، breaker | Http::timeout()->connectTimeout()->retry() |
| Telemetry | SDK مربوط به OpenTelemetry، exporter از نوع OTLP | فیلدهای Context، ارسال traceparent |
| داده | schema و نقش خودش | دیتابیس و migration خودش |
مرز در سطح دیتابیس
مالکیت اعمال میشود، نه وعده داده میشود: هر سرویس با نقشی (role) وصل میشود که فقط schema خودش را میبیند. outbox در همان دیتابیس سفارشهاست، پس یک تراکنش محلی هر دو را مینویسد (نحو PostgreSQL):
-- One PostgreSQL cluster, one schema and one login role per service.
CREATE SCHEMA orders; CREATE ROLE orders_svc LOGIN PASSWORD 'from-secret-store';
CREATE SCHEMA catalog; CREATE ROLE catalog_svc LOGIN PASSWORD 'from-secret-store';
GRANT USAGE, CREATE ON SCHEMA orders TO orders_svc;
GRANT USAGE, CREATE ON SCHEMA catalog TO catalog_svc;
REVOKE ALL ON SCHEMA catalog FROM orders_svc; -- Orders reads prices via the API only
CREATE TABLE orders.orders (
id uuid PRIMARY KEY,
customer_id text NOT NULL,
sku text NOT NULL,
qty int NOT NULL CHECK (qty > 0),
price_cents bigint NOT NULL, -- snapshot copied from Catalog at order time
total_cents bigint NOT NULL,
currency char(3) NOT NULL,
status text NOT NULL DEFAULT 'PENDING'
);
CREATE TABLE orders.outbox (
id uuid PRIMARY KEY,
type text NOT NULL, -- 'OrderPlaced.v1'
payload jsonb NOT NULL,
traceparent text, -- keeps the trace across the async hop
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
BEGIN;
INSERT INTO orders.orders (id, customer_id, sku, qty, price_cents, total_cents, currency)
VALUES ('9727e043-8486-e0fe-e67f-d0c58d9f590e', 'c-42', 'sku-1', 2, 1299, 2598, 'EUR');
INSERT INTO orders.outbox (id, type, payload, traceparent)
VALUES ('72c17966-c8d9-baf5-8159-08985f2adf02', 'OrderPlaced.v1',
'{"order_id":"9727e043","total_cents":2598}', '00-79fb3fa75555fc8ac1b7425491632b9c-0102030405060708-01');
COMMIT;MySQL schema جدا از database ندارد، پس برای هر سرویس یک database بسازید و از GRANT ... ON orders_db.* استفاده کنید؛ MongoDB یک database برای هر سرویس با دسترسی مبتنی بر نقش دارد. relayای که outbox را میخواند در Transactional Outbox است.
تنظیمات (knobs)
| تنظیم | کجا | پیشفرض | این صفحه | چرا |
|---|---|---|---|---|
http.Client.Timeout | net/http در Go | 0 (بدون timeout) | context.WithTimeout برای هر تلاش 300 ms | هرگز تا ابد منتظر وابستگی نمان |
http.Server.ReadHeaderTimeout | net/http در Go | 0 | 5 s | محافظت در برابر Slowloris |
| تعداد تلاش / پایهٔ retry | resilience.Retry | n/a | 2 تلاش، full jitter با 50 ms | فقط خواندنهای idempotent را retry کن |
| آستانه / خنکشدن breaker | resilience.Breaker | n/a | 5 خطا / 10 s | وقتی وابستگی پایین است سریع شکست بخور |
Http::timeout() | HTTP client در Laravel | 30 s | 3 s | مستندات: "By default, the HTTP client will timeout after 30 seconds" |
Http::connectTimeout() | HTTP client در Laravel | 10 s | 1 s | میزبان مرده را سریع تشخیص بده |
Http::retry() | HTTP client در Laravel | بدون retry | [100, 300] ms، فقط روی ConnectionException | capture را بدون idempotency key هرگز retry نکن |
expiration در Sanctum | config/sanctum.php | null (هرگز) | 30 روز برای هر توکن ماشینی | چرخش؛ sanctum:prune-expired پاک میکند |
maxUnavailable / maxSurge | Deployment در Kubernetes | 25% / 25% | 0 / 1 | هنگام rollout ظرفیت هرگز کم نشود |
readinessProbe.periodSeconds | Kubernetes | 10 s | 2 s | تأخیر تخلیه در Serve باید بیشتر از آن باشد |
terminationGracePeriodSeconds | Pod در Kubernetes | 30 s | 30 s | بیشتر از تخلیه + درخواستهای در جریان |
--max-requests | Octane | 500 | 500 | بازیافت workerها برای مهار نشت حافظه |
کدهای خطا و پیامهایی که واقعاً میبینید
| کجا | پیام یا کد | معنا | Retry؟ |
|---|---|---|---|
| کلاینت Go | dial tcp [::1]:18081: connect: connection refused | چیزی گوش نمیدهد (سرویس پایین است) | بله، محدود؛ بعد breaker |
| کلاینت Go | context deadline exceeded | timeout هر تلاش رسید (وابستگی کند) | بله اگر idempotent است |
| این صفحه | circuit breaker is open | شکست سریع، بدون فراخوانی شبکه | نه (تا پایان خنکشدن صبر کن) |
| HTTP | 503 + Retry-After | وابستگی در دسترس نیست یا breaker باز است | بله، بعد از تأخیر |
| HTTP | 504 Gateway Timeout | gateway یا mesh از upstream قطع امید کرد | شاید؛ idempotency را بررسی کن |
| HTTP | 429 Too Many Requests | محدودیت نرخ | بله، بعد از Retry-After |
| HTTP | 409 Conflict | idempotency key با بدنهٔ دیگر دوباره آمده، یا تعارض حالت | نه |
| HTTP | 401 / 403 | توکن نیست / توکن ability لازم را ندارد (middleware abilities در Sanctum) | نه |
| Laravel | Illuminate\Http\Client\ConnectionException | timeout یا خطای اتصال | بله (callback when همین صفحه) |
| Laravel | Illuminate\Http\Client\RequestException | همهٔ retryها با 4xx/5xx شکست خوردند | دیگر نه |
| Kubernetes | Readiness probe failed: HTTP probe failed with statuscode: 503 | pod از endpointهای Service حذف شد | خودکار |
| Kubernetes | CrashLoopBackOff | liveness یا startup مدام شکست میخورد؛ ریاستارتها عقبنشینی میکنند | علت را رفع کن |
Go
مثال کامل: پلتفرم سفارشگیری که به Orders، Catalog، Billing و Notifications شکسته شده است. ماژول Go در docs/snippets/architecture/microservices-architecture/go شامل Orders، Catalog و Notifications است؛ Billing سرویس Laravel بخش بعد است. gofmt -l .، go vet ./... و go test ./... پاس میشوند. یک ماژول Go برای سه سرویس فقط راحتی آزمایشگاه است: در production هر سرویس repository یا ماژول، go.mod، image و pipeline خودش را دارد تا بشود تنها منتشرش کرد.
Chassis: tracing، correlation، health، خاموشی
همهٔ سرویسها همین پکیج کوچک را import میکنند. بخش tracing، propagator استاندارد W3C را نصب میکند و اگر OTEL_EXPORTER_OTLP_ENDPOINT تنظیم شده باشد یک exporter از نوع OTLP/HTTP (در فایل compose، Jaeger):
// Package platform is the small "microservice chassis" every service in the
// lab shares: tracing, correlation IDs, structured logs, health and shutdown.
package platform
import (
"context"
"os"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
// SetupTracing installs a global TracerProvider and the W3C Trace Context
// propagator (traceparent/tracestate headers). Without a collector the
// provider still creates trace IDs, so logs can be correlated; with
// OTEL_EXPORTER_OTLP_ENDPOINT set (e.g. http://jaeger:4318) spans are
// exported over OTLP/HTTP.
func SetupTracing(ctx context.Context, service string) (func(context.Context) error, error) {
res, err := resource.New(ctx, resource.WithAttributes(attribute.String("service.name", service)))
if err != nil {
return nil, err
}
opts := []sdktrace.TracerProviderOption{
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
}
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" {
exp, err := otlptracehttp.New(ctx) // reads the standard OTEL_* env vars
if err != nil {
return nil, err
}
opts = append(opts, sdktrace.WithBatcher(exp))
}
tp := sdktrace.NewTracerProvider(opts...)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{},
))
return tp.Shutdown, nil
}برای هر درخواست یک خط لاگ JSON با trace_id و correlation_id؛ و یک transport خروجی که correlation ID را جلو میبرد:
package platform
import (
"context"
"crypto/rand"
"encoding/hex"
"log/slog"
"net/http"
"time"
"go.opentelemetry.io/otel/trace"
)
// HeaderCorrelationID is the business-level request ID that travels with
// every call (the trace ID is the technical one; we log both).
const HeaderCorrelationID = "X-Correlation-ID"
type ctxKey struct{}
// CorrelationID returns the ID stored in ctx, or "".
func CorrelationID(ctx context.Context) string {
id, _ := ctx.Value(ctxKey{}).(string)
return id
}
// WithCorrelationID stores id in ctx.
func WithCorrelationID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, ctxKey{}, id)
}
// NewID returns 16 random bytes, hex encoded.
func NewID() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// TraceID returns the current trace ID or "".
func TraceID(ctx context.Context) string {
sc := trace.SpanContextFromContext(ctx)
if !sc.IsValid() {
return ""
}
return sc.TraceID().String()
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
// AccessLog accepts or creates the correlation ID, echoes it back, and
// writes one structured log line per request with trace_id and correlation_id.
// Mount it inside otelhttp.NewHandler so the server span is already in ctx.
func AccessLog(log *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(HeaderCorrelationID)
if id == "" {
id = NewID()
}
ctx := WithCorrelationID(r.Context(), id)
w.Header().Set(HeaderCorrelationID, id)
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
next.ServeHTTP(rec, r.WithContext(ctx))
log.InfoContext(ctx, "http",
"method", r.Method, "path", r.URL.Path, "status", rec.status,
"duration_ms", time.Since(start).Milliseconds(),
"trace_id", TraceID(ctx), "correlation_id", id)
})
}
}
// CorrelationTransport copies the correlation ID from the request context to
// the outgoing request. Wrap it with otelhttp.NewTransport for traceparent.
type CorrelationTransport struct{ Base http.RoundTripper }
// RoundTrip implements http.RoundTripper.
func (t CorrelationTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if id := CorrelationID(r.Context()); id != "" && r.Header.Get(HeaderCorrelationID) == "" {
r = r.Clone(r.Context())
r.Header.Set(HeaderCorrelationID, id)
}
base := t.Base
if base == nil {
base = http.DefaultTransport
}
return base.RoundTrip(r)
}Liveness و readiness دو سؤال متفاوتاند؛ readiness فقط چیزی را بررسی میکند که مال خود سرویس است:
package platform
import (
"context"
"encoding/json"
"net/http"
"sync/atomic"
"time"
)
// Check verifies one dependency the service OWNS (its database, its broker
// connection). Never put another service here: a readiness probe that calls
// downstream services turns one outage into a fleet-wide one.
type Check func(ctx context.Context) error
// Health serves /livez (process alive) and /readyz (may receive traffic).
type Health struct {
ready atomic.Bool
checks map[string]Check
}
// NewHealth returns a Health that is not ready until SetReady(true).
func NewHealth(checks map[string]Check) *Health {
return &Health{checks: checks}
}
// SetReady flips readiness (false during startup and graceful shutdown).
func (h *Health) SetReady(v bool) { h.ready.Store(v) }
// Live answers 200 while the process can serve HTTP at all.
func (h *Health) Live(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
}
// Ready answers 200 only when started, not draining, and own checks pass.
func (h *Health) Ready(w http.ResponseWriter, r *http.Request) {
result := map[string]string{}
status := http.StatusOK
if !h.ready.Load() {
status = http.StatusServiceUnavailable
result["lifecycle"] = "not ready"
}
ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
defer cancel()
for name, check := range h.checks {
if err := check(ctx); err != nil {
status = http.StatusServiceUnavailable
result[name] = err.Error()
continue
}
result[name] = "ok"
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(result)
}خاموشی آرام: اول unready شو، بهاندازهٔ دورهٔ probe صبر کن، بعد تخلیه کن:
package platform
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"time"
)
// Serve runs srv until ctx is cancelled (SIGTERM from Docker or Kubernetes),
// then marks the service unready, waits for load balancers to notice, and
// drains in-flight requests.
func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, h *Health, drainDelay time.Duration) error {
ln, err := net.Listen("tcp", srv.Addr) // fail before claiming readiness
if err != nil {
return err
}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
h.SetReady(true)
log.Info("listening", "addr", srv.Addr)
select {
case err := <-errc:
return err
case <-ctx.Done():
}
h.SetReady(false)
time.Sleep(drainDelay) // readiness probe period: stop new traffic first
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
log.Info("stopped")
return nil
}تابآوری: breaker و retry
// Package resilience holds the two client-side stability patterns the lab
// needs: a circuit breaker and retries with jittered backoff.
package resilience
import (
"errors"
"sync"
"time"
)
// ErrOpen is returned without calling the dependency while the breaker is open.
var ErrOpen = errors.New("circuit breaker is open")
// State of a Breaker.
type State int
// Breaker states.
const (
Closed State = iota
Open
HalfOpen
)
func (s State) String() string {
switch s {
case Open:
return "open"
case HalfOpen:
return "half-open"
default:
return "closed"
}
}
// Breaker trips after Threshold consecutive failures, rejects calls for
// Cooldown, then lets exactly one trial call through (half-open).
type Breaker struct {
Threshold int
Cooldown time.Duration
Now func() time.Time // injectable clock for tests
mu sync.Mutex
state State
failures int
openedAt time.Time
trial bool
}
// NewBreaker returns a closed breaker.
func NewBreaker(threshold int, cooldown time.Duration) *Breaker {
return &Breaker{Threshold: threshold, Cooldown: cooldown, Now: time.Now}
}
// State reports the current state (for logs and metrics).
func (b *Breaker) State() State {
b.mu.Lock()
defer b.mu.Unlock()
return b.state
}
// Do runs fn unless the breaker is open.
func (b *Breaker) Do(fn func() error) error {
if err := b.before(); err != nil {
return err
}
err := fn()
b.after(err)
return err
}
func (b *Breaker) before() error {
b.mu.Lock()
defer b.mu.Unlock()
switch b.state {
case Open:
if b.Now().Sub(b.openedAt) < b.Cooldown {
return ErrOpen
}
b.state = HalfOpen
b.trial = true
return nil
case HalfOpen:
if b.trial {
return ErrOpen // one trial call at a time
}
b.trial = true
}
return nil
}
func (b *Breaker) after(err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err == nil {
b.state, b.failures, b.trial = Closed, 0, false
return
}
b.failures++
if b.state == HalfOpen || b.failures >= b.Threshold {
b.state, b.openedAt, b.trial = Open, b.Now(), false
}
}package resilience
import (
"context"
"errors"
"math/rand/v2"
"time"
)
type permanent struct{ err error }
func (p permanent) Error() string { return p.err.Error() }
func (p permanent) Unwrap() error { return p.err }
// Permanent marks an error that must not be retried (4xx, open breaker).
func Permanent(err error) error { return permanent{err} }
// Retry calls fn up to attempts times with "full jitter" exponential backoff
// (sleep a random duration in [0, base*2^n)). It stops early on a Permanent
// error or when ctx is done. Only retry idempotent operations.
func Retry(ctx context.Context, attempts int, base time.Duration, fn func(context.Context) error) error {
var err error
for n := 0; n < attempts; n++ {
if err = fn(ctx); err == nil {
return nil
}
var p permanent
if errors.As(err, &p) {
return p.err
}
if n == attempts-1 {
break
}
sleep := time.Duration(rand.Int64N(int64(base) << n))
select {
case <-ctx.Done():
return errors.Join(err, ctx.Err())
case <-time.After(sleep):
}
}
return err
}package resilience
import (
"errors"
"testing"
"time"
)
func TestBreakerOpensAndRecovers(t *testing.T) {
now := time.Unix(0, 0)
b := NewBreaker(3, 5*time.Second)
b.Now = func() time.Time { return now }
boom := errors.New("timeout")
for i := 0; i < 3; i++ {
_ = b.Do(func() error { return boom })
}
if b.State() != Open {
t.Fatalf("want open, got %v", b.State())
}
called := false
if err := b.Do(func() error { called = true; return nil }); !errors.Is(err, ErrOpen) || called {
t.Fatalf("open breaker must fail fast without calling, err=%v called=%v", err, called)
}
now = now.Add(6 * time.Second) // cooldown elapsed: one trial call
if err := b.Do(func() error { return nil }); err != nil {
t.Fatalf("trial call: %v", err)
}
if b.State() != Closed {
t.Fatalf("want closed after successful trial, got %v", b.State())
}
}
func TestHalfOpenFailureReopens(t *testing.T) {
now := time.Unix(0, 0)
b := NewBreaker(1, time.Second)
b.Now = func() time.Time { return now }
_ = b.Do(func() error { return errors.New("x") })
now = now.Add(2 * time.Second)
_ = b.Do(func() error { return errors.New("still down") })
if b.State() != Open {
t.Fatalf("failed trial must reopen, got %v", b.State())
}
}Catalog: تأمینکننده و کلاینتش
Catalog مالک محصولات است و یک نمایش (representation) منتشر میکند، نه جدولش را. کلاینتی که Orders استفاده میکند timeout هر تلاش، retry و breaker را ترکیب میکند و tolerant میخواند:
// Package catalog is the Catalog service: it owns products and prices.
// Other services read them only through this API, never from its database.
package catalog
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/go-chi/chi/v5"
)
// Product is the published representation (the contract), not the table row.
type Product struct {
SKU string `json:"sku"`
Name string `json:"name"`
PriceCents int64 `json:"price_cents"`
Currency string `json:"currency"`
}
// Store is an in-memory stand-in for Catalog's private database.
type Store struct {
mu sync.RWMutex
products map[string]Product
}
// NewStore returns a store seeded with products.
func NewStore(seed ...Product) *Store {
s := &Store{products: map[string]Product{}}
for _, p := range seed {
s.products[p.SKU] = p
}
return s
}
func (s *Store) get(sku string) (Product, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
p, ok := s.products[sku]
return p, ok
}
// Routes mounts the provider side of the contract. delay simulates a slow
// dependency (used by the lab to trigger client timeouts).
func Routes(r chi.Router, s *Store, delay func() time.Duration) {
r.Get("/products/{sku}", func(w http.ResponseWriter, req *http.Request) {
if d := delay(); d > 0 {
select {
case <-time.After(d):
case <-req.Context().Done():
return
}
}
w.Header().Set("Content-Type", "application/json")
p, ok := s.get(chi.URLParam(req, "sku"))
if !ok {
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "product_not_found"})
return
}
_ = json.NewEncoder(w).Encode(p)
})
}package catalog
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"time"
"academy/microservices-architecture/internal/platform"
"academy/microservices-architecture/internal/resilience"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
// ErrNotFound is the consumer-side meaning of a 404 from Catalog.
var ErrNotFound = errors.New("catalog: product not found")
// Client is the consumer side used by Orders. Every remote call has a
// per-attempt timeout, bounded retries with jitter, and a circuit breaker.
type Client struct {
BaseURL string
HTTP *http.Client
Breaker *resilience.Breaker
PerTry time.Duration
Attempts int
RetryDelay time.Duration
}
// NewClient wires the defaults used in the lab.
func NewClient(baseURL string) *Client {
return &Client{
BaseURL: baseURL,
HTTP: &http.Client{
// otelhttp injects traceparent; CorrelationTransport adds X-Correlation-ID.
Transport: otelhttp.NewTransport(platform.CorrelationTransport{}),
},
Breaker: resilience.NewBreaker(5, 10*time.Second),
PerTry: 300 * time.Millisecond,
Attempts: 2,
RetryDelay: 50 * time.Millisecond,
}
}
// GetProduct is a safe, idempotent read, so retrying it is allowed.
func (c *Client) GetProduct(ctx context.Context, sku string) (Product, error) {
var p Product
err := resilience.Retry(ctx, c.Attempts, c.RetryDelay, func(ctx context.Context) error {
err := c.Breaker.Do(func() error {
var err error
p, err = c.once(ctx, sku)
if errors.Is(err, ErrNotFound) {
return nil // a 404 is an answer, not a failure of Catalog
}
return err
})
if errors.Is(err, resilience.ErrOpen) {
return resilience.Permanent(err) // fail fast, do not hammer
}
return err
})
if err == nil && p.SKU == "" {
return p, ErrNotFound
}
return p, err
}
func (c *Client) once(ctx context.Context, sku string) (Product, error) {
ctx, cancel := context.WithTimeout(ctx, c.PerTry)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/products/"+url.PathEscape(sku), nil)
if err != nil {
return Product{}, err
}
req.Header.Set("Accept", "application/json")
res, err := c.HTTP.Do(req)
if err != nil {
return Product{}, err // includes context.DeadlineExceeded
}
defer res.Body.Close()
switch {
case res.StatusCode == http.StatusNotFound:
return Product{}, ErrNotFound
case res.StatusCode >= 500:
return Product{}, fmt.Errorf("catalog: status %d", res.StatusCode)
case res.StatusCode != http.StatusOK:
return Product{}, resilience.Permanent(fmt.Errorf("catalog: status %d", res.StatusCode))
}
var p Product
// Tolerant reader: unknown fields are ignored, so Catalog may add fields.
if err := json.NewDecoder(res.Body).Decode(&p); err != nil {
return Product{}, err
}
return p, nil
}Contract test
فایل قرارداد را Orders نوشته؛ هر دو طرف با آن تست میشوند، پس pipeline کاتالوگ پیش از رسیدن یک تغییر شکننده به production شکست میخورد:
{
"consumer": "orders",
"provider": "catalog",
"description": "orders reads a product's price before placing an order",
"request": { "method": "GET", "path": "/products/sku-1" },
"response": {
"status": 200,
"body": { "sku": "sku-1", "name": "Coffee beans 1kg", "price_cents": 1299, "currency": "EUR" }
}
}package catalog_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"academy/microservices-architecture/internal/catalog"
"github.com/go-chi/chi/v5"
)
// contract is the shared file both sides test against (consumer-driven:
// Orders wrote it; Catalog's pipeline must keep it green).
type contract struct {
Request struct {
Method string `json:"method"`
Path string `json:"path"`
} `json:"request"`
Response struct {
Status int `json:"status"`
Body map[string]any `json:"body"`
} `json:"response"`
}
func load(t *testing.T) contract {
t.Helper()
raw, err := os.ReadFile("testdata/orders-gets-product.json")
if err != nil {
t.Fatal(err)
}
var c contract
if err := json.Unmarshal(raw, &c); err != nil {
t.Fatal(err)
}
return c
}
// Consumer side: the Orders client understands the response in the contract.
func TestConsumerOrdersUnderstandsContract(t *testing.T) {
c := load(t)
stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != c.Request.Method || r.URL.Path != c.Request.Path {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}
w.WriteHeader(c.Response.Status)
_ = json.NewEncoder(w).Encode(c.Response.Body)
}))
defer stub.Close()
p, err := catalog.NewClient(stub.URL).GetProduct(context.Background(), "sku-1")
if err != nil {
t.Fatal(err)
}
if p.PriceCents != 1299 || p.Currency != "EUR" {
t.Fatalf("consumer misread contract: %+v", p)
}
}
// Provider side: the real Catalog handler still returns every field Orders uses.
func TestProviderCatalogHonoursContract(t *testing.T) {
c := load(t)
r := chi.NewRouter()
catalog.Routes(r, catalog.NewStore(catalog.Product{
SKU: "sku-1", Name: "Coffee beans 1kg", PriceCents: 1299, Currency: "EUR",
}), func() time.Duration { return 0 })
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(c.Request.Method, c.Request.Path, nil))
if rec.Code != c.Response.Status {
t.Fatalf("status %d, contract says %d", rec.Code, c.Response.Status)
}
var got map[string]any
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
t.Fatal(err)
}
for k, want := range c.Response.Body {
if got[k] != want {
t.Errorf("field %q: got %v, contract says %v", k, got[k], want)
}
}
}Orders: فراخوانیهای sync، دادهٔ مالکیتدار، outbox، relay
Orders از Catalog میخواند (با محافظ) و اگر BILLING_URL تنظیم شده باشد Billing را صدا میزند (توکن ماشینی، Idempotency-Key)؛ آزمایشگاه بدون Billing اجرا میشود. relay eventها را مستقیم با HTTP به Notifications میفرستد و جای message bus تصویر را پر میکند؛ سیستم واقعی به RabbitMQ یا Kafka میفرستد.
// Package orders is the Orders service: it owns orders and their outbox.
package orders
import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"sync"
"time"
"academy/microservices-architecture/internal/catalog"
"academy/microservices-architecture/internal/platform"
"academy/microservices-architecture/internal/resilience"
"github.com/go-chi/chi/v5"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
)
// Order is owned by this service only.
type Order struct {
ID string `json:"id"`
CustomerID string `json:"customer_id"`
SKU string `json:"sku"`
Qty int64 `json:"qty"`
TotalCents int64 `json:"total_cents"`
Currency string `json:"currency"`
// PriceCents is copied from Catalog at order time: Orders keeps its own
// snapshot instead of joining Catalog's table later.
PriceCents int64 `json:"price_cents"`
}
// Event is an integration event waiting in the outbox.
type Event struct {
ID string `json:"id"`
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
Trace map[string]string `json:"-"` // traceparent carried across the async hop
Sent bool `json:"-"`
}
// Store stands in for the Orders database: the order row and the outbox row
// are written under one lock, the way one SQL transaction would write both.
type Store struct {
mu sync.Mutex
orders map[string]Order
outbox []*Event
}
// NewStore returns an empty store.
func NewStore() *Store { return &Store{orders: map[string]Order{}} }
func (s *Store) placeWithEvent(ctx context.Context, o Order) error {
payload, err := json.Marshal(o)
if err != nil {
return err
}
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
s.mu.Lock()
defer s.mu.Unlock()
s.orders[o.ID] = o
s.outbox = append(s.outbox, &Event{ID: platform.NewID(), Type: "OrderPlaced.v1", Payload: payload, Trace: carrier})
return nil
}
// Catalog is the port Orders needs; *catalog.Client implements it.
type Catalog interface {
GetProduct(ctx context.Context, sku string) (catalog.Product, error)
}
type placeRequest struct {
CustomerID string `json:"customer_id"`
SKU string `json:"sku"`
Qty int64 `json:"qty"`
}
// Billing is the port for charging; nil means "not configured" (the lab
// runs without the Laravel service).
type Billing interface {
Charge(ctx context.Context, o Order) error
}
// Routes mounts POST /orders.
func Routes(r chi.Router, log *slog.Logger, s *Store, cat Catalog, bill Billing) {
r.Post("/orders", func(w http.ResponseWriter, req *http.Request) {
var in placeRequest
if err := json.NewDecoder(req.Body).Decode(&in); err != nil || in.SKU == "" || in.Qty <= 0 {
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "invalid_order"})
return
}
p, err := cat.GetProduct(req.Context(), in.SKU)
switch {
case errors.Is(err, catalog.ErrNotFound):
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "unknown_sku"})
return
case errors.Is(err, resilience.ErrOpen):
// Fail fast: the breaker already knows Catalog is down.
w.Header().Set("Retry-After", "10")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "catalog_unavailable", "breaker": "open"})
return
case err != nil:
log.WarnContext(req.Context(), "catalog call failed", "err", err, "trace_id", platform.TraceID(req.Context()))
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "catalog_unavailable"})
return
}
o := Order{
ID: platform.NewID(), CustomerID: in.CustomerID, SKU: p.SKU, Qty: in.Qty,
PriceCents: p.PriceCents, TotalCents: p.PriceCents * in.Qty, Currency: p.Currency,
}
if bill != nil {
// Synchronous: the customer must know now whether payment worked.
// The Idempotency-Key makes a retry of this call safe; making a
// client's retry of POST /orders safe needs a client-supplied key
// (see the API Idempotency chapter).
if err := bill.Charge(req.Context(), o); err != nil {
log.WarnContext(req.Context(), "billing call failed", "err", err, "trace_id", platform.TraceID(req.Context()))
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "payment_failed"})
return
}
}
if err := s.placeWithEvent(req.Context(), o); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "store_failed"})
return
}
writeJSON(w, http.StatusCreated, o)
})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// Relay publishes outbox events to Notifications at least once. If
// Notifications is down, orders still succeed; events wait and are retried.
// (A real system relays to a broker; see the outbox and messaging chapters.)
func Relay(ctx context.Context, log *slog.Logger, s *Store, client *http.Client, notificationsURL string, every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
s.mu.Lock()
pending := make([]*Event, 0, len(s.outbox))
for _, e := range s.outbox {
if !e.Sent {
pending = append(pending, e)
}
}
s.mu.Unlock()
for _, e := range pending {
// Continue the trace of the request that created the event.
ectx := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(e.Trace))
if err := deliver(ectx, client, notificationsURL, e); err != nil {
log.WarnContext(ectx, "relay: will retry", "event_id", e.ID, "err", err, "trace_id", platform.TraceID(ectx))
break // keep order; try again on next tick
}
s.mu.Lock()
e.Sent = true
s.mu.Unlock()
}
}
}
func deliver(ctx context.Context, client *http.Client, base string, e *Event) error {
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
body, err := json.Marshal(e)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/events", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 300 {
return errors.New("notifications: status " + res.Status)
}
return nil
}package orders
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// BillingClient calls the Laravel Billing service. The Sanctum token is a
// machine token with the "charges:create" ability, read from a secret at
// start-up. The Idempotency-Key is the order ID, so a retried call can never
// capture twice; Billing returns the first result for a repeated key.
type BillingClient struct {
BaseURL string
Token string
HTTP *http.Client
Timeout time.Duration
}
type chargeRequest struct {
OrderID string `json:"order_id"`
AmountCents int64 `json:"amount_cents"`
Currency string `json:"currency"`
}
// Charge returns nil when Billing answered 200 (replay) or 201 (created).
func (b *BillingClient) Charge(ctx context.Context, o Order) error {
ctx, cancel := context.WithTimeout(ctx, b.Timeout)
defer cancel()
body, err := json.Marshal(chargeRequest{OrderID: o.ID, AmountCents: o.TotalCents, Currency: o.Currency})
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.BaseURL+"/api/charges", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+b.Token)
req.Header.Set("Idempotency-Key", "charge-"+o.ID)
res, err := b.HTTP.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
return fmt.Errorf("billing: status %d", res.StatusCode)
}
return nil
}// Command orders runs the Orders service: it calls Catalog synchronously
// (it needs the price now) and tells Notifications asynchronously (via outbox).
package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/microservices-architecture/internal/catalog"
"academy/microservices-architecture/internal/orders"
"academy/microservices-architecture/internal/platform"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "orders")
shutdown, err := platform.SetupTracing(ctx, "orders")
if err != nil {
log.Error("tracing", "err", err)
os.Exit(1)
}
defer func() { _ = shutdown(context.Background()) }()
cat := catalog.NewClient(env("CATALOG_URL", "http://localhost:8081"))
store := orders.NewStore()
outbound := &http.Client{Transport: otelhttp.NewTransport(platform.CorrelationTransport{})}
// Billing (Laravel) is optional so the lab runs with three Go services.
var bill orders.Billing
if url := os.Getenv("BILLING_URL"); url != "" {
bill = &orders.BillingClient{BaseURL: url, Token: os.Getenv("BILLING_TOKEN"), HTTP: outbound, Timeout: 2 * time.Second}
}
go orders.Relay(ctx, log, store, outbound, env("NOTIFICATIONS_URL", "http://localhost:8082"), time.Second)
// Readiness checks only what Orders owns (here: nothing external).
// Catalog being down must NOT make Orders unready, or the whole fleet drops.
health := platform.NewHealth(nil)
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Get("/livez", health.Live)
r.Get("/readyz", health.Ready)
r.Group(func(r chi.Router) {
r.Use(platform.AccessLog(log))
orders.Routes(r, log, store, cat, bill)
})
srv := &http.Server{
Addr: ":" + env("PORT", "8080"),
Handler: otelhttp.NewHandler(r, "orders"),
ReadHeaderTimeout: 5 * time.Second,
}
if err := platform.Serve(ctx, log, srv, health, 2*time.Second); err != nil {
log.Error("serve", "err", err)
os.Exit(1)
}
}
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}// Command catalog runs the Catalog service (owns products and prices).
package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"academy/microservices-architecture/internal/catalog"
"academy/microservices-architecture/internal/platform"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "catalog")
shutdown, err := platform.SetupTracing(ctx, "catalog")
if err != nil {
log.Error("tracing", "err", err)
os.Exit(1)
}
defer func() { _ = shutdown(context.Background()) }()
// SLOW_MS lets the lab make Catalog slow without killing it.
slow, _ := strconv.Atoi(os.Getenv("SLOW_MS"))
store := catalog.NewStore(
catalog.Product{SKU: "sku-1", Name: "Coffee beans 1kg", PriceCents: 1299, Currency: "EUR"},
catalog.Product{SKU: "sku-2", Name: "Grinder", PriceCents: 8900, Currency: "EUR"},
)
health := platform.NewHealth(nil)
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Get("/livez", health.Live)
r.Get("/readyz", health.Ready)
r.Group(func(r chi.Router) {
r.Use(platform.AccessLog(log))
catalog.Routes(r, store, func() time.Duration { return time.Duration(slow) * time.Millisecond })
})
srv := &http.Server{
Addr: ":" + env("PORT", "8081"),
Handler: otelhttp.NewHandler(r, "catalog"),
ReadHeaderTimeout: 5 * time.Second,
}
if err := platform.Serve(ctx, log, srv, health, 2*time.Second); err != nil {
log.Error("serve", "err", err)
os.Exit(1)
}
}
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}// Command notifications consumes OrderPlaced events. It is idempotent:
// the relay delivers at least once, so duplicates are expected.
package main
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"academy/microservices-architecture/internal/platform"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
type event struct {
ID string `json:"id"`
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "notifications")
shutdown, err := platform.SetupTracing(ctx, "notifications")
if err != nil {
log.Error("tracing", "err", err)
os.Exit(1)
}
defer func() { _ = shutdown(context.Background()) }()
var mu sync.Mutex
seen := map[string]bool{} // inbox: in production a table with a unique key
health := platform.NewHealth(nil)
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Get("/livez", health.Live)
r.Get("/readyz", health.Ready)
r.Group(func(r chi.Router) {
r.Use(platform.AccessLog(log))
r.Post("/events", func(w http.ResponseWriter, req *http.Request) {
var e event
if err := json.NewDecoder(req.Body).Decode(&e); err != nil || e.ID == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
mu.Lock()
dup := seen[e.ID]
seen[e.ID] = true
mu.Unlock()
if !dup && e.Type == "OrderPlaced.v1" {
log.InfoContext(req.Context(), "email queued", "event_id", e.ID, "trace_id", platform.TraceID(req.Context()))
}
w.WriteHeader(http.StatusAccepted)
})
})
srv := &http.Server{
Addr: ":" + env("PORT", "8082"),
Handler: otelhttp.NewHandler(r, "notifications"),
ReadHeaderTimeout: 5 * time.Second,
}
if err := platform.Serve(ctx, log, srv, health, 2*time.Second); err != nil {
log.Error("serve", "err", err)
os.Exit(1)
}
}
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}بستهبندی و محیط آزمایشگاه
# One image per service: docker build --build-arg SERVICE=orders -t orders .
FROM golang:1.26 AS build
ARG SERVICE
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/${SERVICE}
FROM alpine:3.20
RUN adduser -D -u 10001 app
COPY --from=build /out/app /app
USER app
ENTRYPOINT ["/app"]# Lab: three Go services plus Jaeger. `docker compose up --build`
# Jaeger UI: http://localhost:16686 (traces arrive over OTLP/HTTP on 4318)
x-otel: &otel
OTEL_EXPORTER_OTLP_ENDPOINT: http://jaeger:4318
services:
catalog:
build: { context: ./go, args: { SERVICE: catalog } }
environment: { <<: *otel, PORT: "8081", SLOW_MS: "${CATALOG_SLOW_MS:-0}" }
ports: ["8081:8081"]
notifications:
build: { context: ./go, args: { SERVICE: notifications } }
environment: { <<: *otel, PORT: "8082" }
ports: ["8082:8082"]
orders:
build: { context: ./go, args: { SERVICE: orders } }
environment:
<<: *otel
PORT: "8080"
CATALOG_URL: http://catalog:8081
NOTIFICATIONS_URL: http://notifications:8082
ports: ["8080:8080"]
depends_on: [catalog, notifications]
jaeger:
image: jaegertracing/all-in-one:1.62.0
environment: { COLLECTOR_OTLP_ENABLED: "true" }
ports: ["16686:16686", "4318:4318"]نگاه Go
| ویژگی یا کتابخانهٔ Go | نقش در یک میکروسرویس |
|---|---|
Server از net/http با ReadHeaderTimeout و Shutdown | سرور HTTP آمادهٔ production و تخلیهٔ آرام، بدون نیاز به framework |
chi (github.com/go-chi/chi/v5) | router "built on the new context package"؛ سازگار با handler و middlewareهای net/http |
context | ضربالاجل و لغو از درخواست ورودی به هر فراخوانی خروجی جاری میشود |
log/slog | لاگ JSON ساختیافته با trace_id و correlation_id |
OpenTelemetry Go (otel، sdk/trace، otelhttp) | span و انتقال W3C برای سرور و کلاینت |
| grpc-go | قرارداد typeدار در .proto، deadline و interceptor برای فراخوانیهای داخلی (gRPC) |
encoding/json | بهطور پیشفرض فیلد ناشناخته را نادیده میگیرد: tolerant reader مجانی |
| باینری ایستا، imageهای distroless | image کوچک، شروع سریع، CVE کمتر |
Laravel
Billing یک برنامهٔ Laravel 13 (PHP 8.4) است که Octane سرویسش میدهد. فایلها در docs/snippets/architecture/microservices-architecture/php هستند؛ PHP روی ماشین نویسنده نصب نیست، پس کد در برابر مستندات Laravel 13 بازبینی شده، اجرا نشده است. به گفتهٔ مستندات، Octane "boots your application once, keeps it in memory, and then feeds it requests at supersonic speeds"، و به همین دلیل دادهٔ هر درخواست هرگز نباید در constructor یا singleton گیر بیفتد.
سیمکشی: مسیر health، middleware ability، correlation
bootstrap/app.php مسیر health یعنی /up و aliasهای ability را که مستندات Sanctum تعریف میکند فعال میکند:
<?php
use App\Http\Middleware\CorrelationContext;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
// Billing service (Laravel 13, served by Octane + FrankenPHP).
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up', // 200 when the app boots; DiagnosingHealth listeners add checks
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'abilities' => CheckAbilities::class,
'ability' => CheckForAnyAbility::class,
]);
$middleware->append(CorrelationContext::class);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();<?php
use App\Http\Controllers\ChargeController;
use Illuminate\Support\Facades\Route;
// Machine-to-machine: only a token carrying the "charges:create" ability
// (issued to the Orders service) may create charges.
Route::post('/charges', ChargeController::class)
->middleware(['auth:sanctum', 'abilities:charges:create']);middleware مربوط به correlation در Context لاراول مینویسد، که فیلدها را به هر خط لاگ اضافه میکند و به jobهای صف هم میبرد:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
/**
* Accepts the caller's correlation ID and W3C traceparent, puts them in
* Laravel's Context (added to every log line and carried into queued jobs),
* and echoes the correlation ID back.
*
* Octane keeps the app in memory between requests: never store these values
* in a singleton or constructor; Context is per request.
*/
final class CorrelationContext
{
public function handle(Request $request, Closure $next): Response
{
$id = $request->header('X-Correlation-ID') ?: (string) Str::uuid();
Context::add('service', 'billing');
Context::add('correlation_id', $id);
if ($traceparent = $request->header('traceparent')) {
Context::add('traceparent', $traceparent);
}
$response = $next($request);
$response->headers->set('X-Correlation-ID', $id);
return $response;
}
}توکنهای ماشینی با Sanctum
هر سرویس فراخواننده هویت خودش و یک توکن محدود و تاریخدار میگیرد (createToken($name, $abilities, $expiresAt))؛ سرویس Orders آن را بهشکل bearer token میفرستد:
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
/**
* php artisan billing:issue-token orders --ability=charges:create
*
* Each calling service gets its own identity (a dedicated user row) and a
* short-lived Sanctum token limited to the abilities it needs. Store the
* plain-text token in the caller's secret store, never in git.
*/
final class IssueServiceToken extends Command
{
protected $signature = 'billing:issue-token {service} {--ability=*} {--days=30}';
protected $description = 'Issue a scoped machine token for a calling service';
public function handle(): int
{
$service = $this->argument('service');
$account = User::firstOrCreate(
['email' => "svc-{$service}@services.internal"],
['name' => "service:{$service}", 'password' => Str::random(64)],
);
$token = $account->createToken(
"{$service}-service",
$this->option('ability') ?: ['charges:create'],
now()->addDays((int) $this->option('days')),
);
$this->line($token->plainTextToken);
return self::SUCCESS;
}
}Endpoint: دادهٔ مالکیتدار، idempotency، فراخوانی خروجی با retry
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Billing's own database: no other service has credentials for it.
return new class extends Migration
{
public function up(): void
{
Schema::create('charges', function (Blueprint $table) {
$table->id();
$table->string('idempotency_key', 64)->unique();
$table->string('order_id', 64)->index();
$table->unsignedBigInteger('amount_cents');
$table->char('currency', 3);
$table->string('psp_reference', 128);
$table->string('status', 16);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('charges');
}
};<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class Charge extends Model
{
protected $fillable = [
'idempotency_key', 'order_id', 'amount_cents', 'currency', 'psp_reference', 'status',
];
/** The published representation: the contract, not the table. */
public function toContract(): array
{
return [
'charge_id' => (string) $this->id,
'order_id' => $this->order_id,
'amount_cents' => (int) $this->amount_cents,
'currency' => $this->currency,
'status' => $this->status,
];
}
}<?php
namespace App\Http\Controllers;
use App\Models\Charge;
use App\Services\PaymentProvider;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
final class ChargeController
{
public function __invoke(Request $request, PaymentProvider $psp): JsonResponse
{
$data = $request->validate([
'order_id' => ['required', 'string', 'max:64'],
'amount_cents' => ['required', 'integer', 'min:1'],
'currency' => ['required', 'string', 'size:3'],
]);
$key = $request->header('Idempotency-Key');
abort_if(! $key, 400, 'Idempotency-Key header is required');
// A retry from Orders with the same key returns the first result.
$existing = Charge::where('idempotency_key', $key)->first();
if ($existing) {
return response()->json($existing->toContract(), 200);
}
$pspReference = $psp->capture($key, $data['amount_cents'], $data['currency']);
$charge = DB::transaction(fn () => Charge::create([
'idempotency_key' => $key, // unique index: a concurrent duplicate fails here
'order_id' => $data['order_id'],
'amount_cents' => $data['amount_cents'],
'currency' => $data['currency'],
'psp_reference' => $pspReference,
'status' => 'captured',
]));
return response()->json($charge->toContract(), 201);
}
}<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Outbound call to the payment provider: explicit timeouts, retries only on
* connection failures, and the same Idempotency-Key on every attempt so a
* retry can never capture twice.
*/
final class PaymentProvider
{
public function capture(string $idempotencyKey, int $amountCents, string $currency): string
{
$response = Http::baseUrl(config('services.psp.url'))
->withToken(config('services.psp.secret'))
->acceptJson()
->connectTimeout(1) // default is 10 seconds
->timeout(3) // default is 30 seconds
->withHeaders([
'Idempotency-Key' => $idempotencyKey,
// Read per call, never cached: Octane reuses this process.
'X-Correlation-ID' => (string) Context::get('correlation_id'),
])
->retry([100, 300], when: function (Throwable $e, PendingRequest $request): bool {
return $e instanceof ConnectionException;
})
->post('/v1/captures', [
'amount' => $amountCents,
'currency' => $currency,
]);
// After the last failed attempt Laravel throws RequestException (4xx/5xx)
// or ConnectionException; the controller lets it become a 5xx for Orders.
return (string) $response->json('reference');
}
}Health و contract test تأمینکننده
<?php
namespace App\Listeners;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;
/**
* Extends GET /up: Billing is healthy only if ITS OWN database answers.
* It deliberately does not call Orders or the payment provider.
*/
final class CheckBillingDependencies
{
public function handle(DiagnosingHealth $event): void
{
DB::select('select 1'); // throws -> /up returns 500
}
}<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Sanctum\Sanctum;
// Provider side of the contract Orders depends on (consumer-driven).
// The JSON shape below is what Orders' Go client sends and expects; keep it green.
// Requires App\Models\User to use Laravel\Sanctum\HasApiTokens.
uses(RefreshDatabase::class);
beforeEach(function () {
config(['services.psp.url' => 'https://psp.test', 'services.psp.secret' => 'test']);
// The real PaymentProvider runs (timeouts, retry rules); only the network is faked.
Http::fake([
'psp.test/*' => Http::response(['reference' => 'psp_123'], 200),
]);
});
test('orders can create a charge and gets the contracted shape', function () {
Sanctum::actingAs(User::factory()->create(), ['charges:create']);
$this->postJson('/api/charges', [
'order_id' => 'o-1', 'amount_cents' => 2598, 'currency' => 'EUR',
], ['Idempotency-Key' => 'charge-o-1'])
->assertCreated()
->assertJsonStructure(['charge_id', 'order_id', 'amount_cents', 'currency', 'status'])
->assertJson(['order_id' => 'o-1', 'amount_cents' => 2598, 'status' => 'captured']);
});
test('a retry with the same idempotency key does not charge twice', function () {
Sanctum::actingAs(User::factory()->create(), ['charges:create']);
$body = ['order_id' => 'o-2', 'amount_cents' => 100, 'currency' => 'EUR'];
$this->postJson('/api/charges', $body, ['Idempotency-Key' => 'charge-o-2'])->assertCreated();
$this->postJson('/api/charges', $body, ['Idempotency-Key' => 'charge-o-2'])->assertOk();
Http::assertSentCount(1); // the payment provider was called once
});
test('a token without the ability is rejected', function () {
Sanctum::actingAs(User::factory()->create(), ['catalog:read']);
$this->postJson('/api/charges', [], ['Idempotency-Key' => 'x'])->assertForbidden();
});نگاه Laravel
| ویژگی Laravel | نقش در یک میکروسرویس | نکته از مستندات Laravel 13 |
|---|---|---|
| Octane (FrankenPHP، RoadRunner، Swoole) | workerهای ماندگار: تأخیر کم برای هر درخواست | register/boot در service providerها یک بار برای هر worker اجرا میشوند؛ container یا request را به singleton تزریق نکنید |
| HTTP client | فراخوانی خروجی | timeout پیشفرض 30 s، connectTimeout پیشفرض 10 s؛ retry($times, $sleep, $when, throw: ...)؛ بعد از آخرین شکست RequestException پرتاب میشود |
| توکنهای API در Sanctum | احراز هویت ماشین به ماشین | توکنها با SHA-256 در دیتابیس hash میشوند؛ ability با tokenCan یا middlewareهای abilities / ability بررسی میشود؛ نصب با php artisan install:api |
facade به نام Context | فیلدهای correlation در لاگ و job | Context در payload جاب صف "dehydrated" میشود |
مسیر health یعنی /up | Probeها | 200 وقتی boot شد، 500 هنگام exception؛ DiagnosingHealth اجازهٔ افزودن بررسی میدهد |
| صفها (Redis، SQS، database...) | کار async درون سرویس | eventهای بین سرویسها brokerی میخواهند که هر دو طرف بفهمند؛ Laravel Queue Internals |
حل مشکلات کلاسیک
«نمیتوانیم یک سرویس را تنها مستقر کنیم» (distributed monolith)
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| تغییرهای سازگار با عقب | tolerant reader، تغییر افزایشی، expand-and-contract | بدون هماهنگی | انضباط؛ فیلدهای دوگانهٔ موقت |
| قراردادهای مصرفکنندهمحور | فایل قرارداد در CI تأمینکننده اجرا میشود | شکست پیش از استقرار گرفته میشود | قراردادها نگهداری میخواهند |
| حذف کتابخانهٔ دامنهٔ مشترک | DTOهای کوچک را تکرار کن؛ فقط کد فنی مشترک باشد | بالا بردن کتابخانه دیگر انتشار اجباری نمیسازد | کمی تکرار |
| ادغام سرویسها | اگر همیشه با هم عوض میشوند، یک سرویساند | سادهترین راه | اعتراف به اینکه مرز غلط بود |
«دو سرویس روی یک جدول مینویسند» (shared database)
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| یک مالک برای هر جدول | دسترسی نوشتن فقط به یک نقش (SQL بالا) | مالکیت روشن | بقیه API لازم دارند |
| API یا event بهجای خواندن | مالک query API میدهد یا تغییرها را منتشر میکند | schema آزادانه عوض میشود | تأخیر، eventual consistency |
| مدل خواندنی / دادهٔ تکثیرشده | مصرفکننده کپی خودش را نگه میدارد (snapshot قیمت) | بدون وابستگی زمان اجرا | باید برای کهنگی داده طراحی کرد |
| خفه کردن تدریجی schema مشترک | جدولها را یکییکی منتقل کن (مالکیت داده) | تدریجی | مهاجرت طولانی |
«یک سرویس کند همه را میخواباند» (cascading failure)
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| timeout روی هر فراخوانی | context.WithTimeout، Http::timeout(3) | انتظار محدود | انتخاب مقدار، دادهٔ تأخیر میخواهد |
| retry محدود با jitter | 2 تلاش، full jitter، فقط idempotent | لرزشهای کوتاه را جذب میکند | اگر نامحدود باشد طوفان retry |
| Circuit breaker | بعد از N خطا سریع شکست بخور | از فراخواننده و فراخوانده محافظت میکند | UX جایگزین (fallback) لازم است |
| Bulkhead | استخر جدا برای هر وابستگی | یک وابستگی نمیتواند همهٔ workerها را مصرف کند | تنظیم بیشتر |
| async بهجای sync | event برای تعاملهای «باخبر کردن» | فراخواننده به uptime فراخوانده وابسته نیست | eventual consistency |
«درخواستم کجا رفت؟» (بدون observability)
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| انتقال trace | OpenTelemetry + traceparent استاندارد W3C در هر پرش، از جمله ردیفهای outbox | یک نمای واحد از درخواست | باید همهٔ سرویسها instrument شوند |
| correlation ID در لاگ | middleware + slog / Context | یک شناسه را در همهٔ سرویسها grep کن | کلاینتها باید جلو ببرندش |
| متریکهای RED برای هر سرویس | نرخ، خطا، مدت برای هر endpoint | هشدار روی علائم | انضباط در cardinality |
| پایش معنایی | متریک کسبوکار: سفارش در دقیقه | شکستهای بیصدا را میگیرد | ورودی کسبوکار میخواهد |
«سرویسهای ریز زیادی داریم» (nanoservices، entity services)
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| بهکار بستن نیروهای تجمیع | تراکنش، workflow، کد مشترک، رابطهٔ داده | فراخوانی راه دور کمتر | سرویسهای بزرگتر |
| برش بر اساس قابلیت | Checkout و Billing بهجای CRUD برای Customer و Order | use caseها درون یک سرویس میمانند | مدلسازی دوباره |
| ادغام بر اساس همتغییری | سرویسهایی که در همان PRها عوض میشوند ادغام شوند | با الگوی تغییر جور است | اعتراف به اشتباه قبلی |
«هر سرویس auth، لاگ و config را جور دیگری انجام میدهد»
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| قالب سرویس + chassis | generatorی که سرویس را با لولهکشی آماده میسازد | سریع، یکدست | هر بار یک زبان |
| Sidecar / mesh | mesh مبتنی بر Envoy (Istio، Linkerd) برای mTLS، retry، متریک | مستقل از زبان | پیچیدگی عملیاتی، تأخیر در هر پرش |
| Platform team | مالک جادهٔ هموار بهعنوان یک محصول | تیمهای stream-aligned سریعتر میروند | تیمی که باید تأمین مالی شود |
انتخاب
| موقعیت | توصیه | تکنیک اضافه | دلیل |
|---|---|---|---|
| محصول تازه، یک تیم، دامنهٔ مبهم | Modular monolith | مرز ماژول، fitness test | «Monolith First»؛ مرزها هنوز معلوم نیستند |
| یک تیم، یک pipeline پرداده | یک پردازه | تحویل درون حافظه بین مرحلهها | Prime Video: توزیع هزینهٔ S3 و orchestration اضافه کرد |
| 3 تا 8 تیم، دامنهٔ پایدار، دعوای انتشار هفتگی | چند سرویس درشتدانه | پلتفرم، قرارداد، CD | مسیر «coarse-grained services» از Fowler؛ استقرار مستقل |
| یک بخش مقیاس یا امنیت خیلی متفاوت لازم دارد | همان یک سرویس را بیرون بکش | strangler fig در لبه | نیروی تجزیه: مقیاس، امنیت |
| تیمهای زیاد، زبانهای زیاد | میکروسرویس با پلتفرم و mesh | تیمهای stream-aligned + platform | استقلال تیم سود اصلی است |
| صدها سرویس | گروهبندی در دامنهها با gateway | gatewayهای دامنه به سبک DOMA | Uber: حدود 2,200 سرویس در 70 دامنه |
| CI/CD نیست، پایش نیست، کشیک نیست | فعلاً نشکن | اول پیشنیازها را بساز | پیشنیازهای Fowler |
| سازگاری قوی در بیشتر عملیات | کنار هم نگه دار | ACID در یک دیتابیس | نیروی تجمیع: تراکنش دیتابیس |
کی میکروسرویس نسازیم: تیم کوچک (روی هم یکی دو پیتزا)، محصول نوپایی که دامنهاش هنوز در حرکت است، نبود خودکارسازی استقرار یا پایش، بار کاریای که تراکنشهای بینموجودیتی غالبش است، بودجهٔ تأخیری که پرشهای شبکه را تحمل نمیکند، یا انگیزهای از جنس «همه این کار را میکنند». مهاجرت از monolith تدریجی است، از لبه، با الگوی strangler fig (نوشتهٔ Fowler با نام «Strangler Fig» که از «Strangler Application» تغییر نام داد و ۲۲ اوت ۲۰۲۴ بهروز شد).
در معماری: از یک پردازه تا سیستم توزیعشده
همان پلتفرم سفارش در هر مرحله. سؤال هر گام: چه چیزی از مرز رد میشود، و وقتی طرف دیگر کند یا پایین است چه میشود؟
Monolith: یک پردازه، یک دیتابیس
چطور ظاهر میشود: Orders، Catalog، Billing و Notifications پکیجهای یک باینری Go یا پوشههای یک برنامهٔ Laravelاند؛ checkout یک زنجیرهٔ فراخوانی تابع و یک BEGIN ... COMMIT است.
سادهترین استفادهٔ درست: پوشهبندی لایهای یا بر اساس قابلیت، یک pipeline، یک داشبورد، scale افقی پشت load balancer.
مثال (ساده): فروشگاه یک نانوایی: Laravel، یک MySQL، ایمیلها با driver دیتابیس در صف.
مثال (در اندازهٔ production): یک سایت فروش منطقهای با ۱۵ توسعهدهنده، یک primary از PostgreSQL و دو replica، چند بار در روز استقرار با blue/green (یادداشت Fowler دربارهٔ Facebook و Etsy: continuous delivery میکروسرویس لازم ندارد).
Modular monolith و چند دیتابیس
چطور ظاهر میشود: هر ماژول schema خودش را دارد و یک facade عرضه میکند؛ یک fitness test دست بردن در جدولهای ماژول دیگر را ممنوع میکند. eventهای بین ماژولها درون پردازهاند. این مرحلهای است که مرزها را ارزان یاد میگیرید (Modular Monolith).
مثال: همان فروشگاه با schemaها و نقشهای orders، catalog و billing مثل SQL بالا، هنوز در یک deployable؛ ماژول Billing بهخاطر دامنهٔ PCI اولین نامزد بیرون کشیدن است (نیروی تجزیهٔ امنیت).
میکروسرویسها: مرز به شبکه تبدیل میشود
چه میماند: APIهای ماژول به API از نوع HTTP یا gRPC تبدیل میشوند؛ eventهای ماژول به پیام broker؛ مالکیت schema به مالکیت دیتابیس.
چه میشکند: تراکنش مشترک (outbox، saga)، تأخیر (هر فراخوانی میلیثانیهها هزینه دارد)، دسترسپذیری (فراخوانیها شکست میخورند)، اشکالزدایی (trace لازم است).
Checkout across services
1 POST /orders orders-svc (Go)
2 GET /products/sku-1 300 ms, breaker catalog-svc (Go)
3 POST /api/charges Bearer token, Idempotency-Key: order-id billing-svc (Laravel)
4 COMMIT order + outbox orders_db
5 relay -> OrderPlaced.v1 -> notifications-svc (dedup by event id)
Failure: step 2 down -> 503 fast (breaker); step 3 down -> order PENDING, saga retries captureمثال production: Uber سرویسهایش را در دامنههایی گروهبندی میکند که هر کدام یک gateway دارند، تا دامنههای دیگر بهجای دهها سرویس داخلی فقط یک gateway را صدا بزنند.
دادهٔ توزیعشده: replica، cache، region
| کجا | چه میشکند | پاسخ طراحی |
|---|---|---|
| replicaهای خواندنی Catalog | قیمت عوض شده، replica هنوز قدیمی است | Orders از قیمتی که استفاده کرده snapshot میگیرد؛ job تطبیق |
| cache محصولات در Orders | قیمت کهنه پس از تغییر | TTL کوتاه، نسخه در کلید، بیاعتبارسازی با event PriceChanged |
| relay مربوط به outbox | تکرار هنگام retry | مصرفکنندهٔ idempotent با جدول inbox |
| چند region | فراخوانی sync بین regionها کند است | هر region یک مجموعهٔ کامل اجرا کند؛ catalog فقطخواندنی تکثیر شود |
| گزارشگیری بین سرویسها | join بین سرویسها وجود ندارد | مدل خواندنی CQRS یا data warehouse که از event/CDC تغذیه شود |
مسیر مقیاس: 1×، 10×، 100×
| مقیاس | ساختار | چه عوض میشود |
|---|---|---|
| 1× (یک تیم) | Modular monolith | ماژول، schema، ADR، یک pipeline |
| 10× (5 تا 8 تیم) | 4 تا 10 سرویس درشت + پلتفرم | pipeline برای هر سرویس، قرارداد، tracing، پیشفرض breaker در chassis |
| 100× (دهها تیم) | صدها سرویس گروهبندیشده در دامنهها | gateway دامنه، mesh با mTLS، کاتالوگ سرویس، SLO و error budget برای هر سرویس |
آزمایشگاه: سه سرویس، یک شکست، یک trace
Orders، Catalog و Notifications را اجرا میکنید، سفارش میدهید، Catalog را میکشید و باز شدن breaker را میبینید، Catalog را کند میکنید، برش میگردانید، Notifications را پایین میآورید و میبینید outbox عقبماندگی را جبران میکند، و در آخر یک trace ID را در هر سه سرویس دنبال میکنید. همهٔ این گامها روی ماشین نویسنده اجرا شده و خروجیها واقعیاند (شناسهها فرق خواهند کرد).
آمادهسازی (Docker لازم نیست):
cd docs/snippets/architecture/microservices-architecture/go
go test ./... # breaker unit tests + contract tests
go build -o /tmp/msa/ ./cmd/...
cd /tmp/msa
PORT=18081 ./catalog > catalog.log 2>&1 &
PORT=18082 ./notifications > notif.log 2>&1 &
PORT=18080 CATALOG_URL=http://localhost:18081 NOTIFICATIONS_URL=http://localhost:18082 ./orders > orders.log 2>&1 &با Docker: docker compose up --build در پوشهٔ snippet (پورتهای 8080 تا 8082، رابط Jaeger روی http://localhost:16686). گامهای زیر با باینریها اجرا شدند؛ مسیر compose build شد اما گامبهگام طی نشد.
گام ۱: مسیر خوش.
curl -s -X POST localhost:18080/orders -H 'X-Correlation-ID: lab-1' \
-d '{"customer_id":"c-42","sku":"sku-1","qty":2}'
# {"id":"b8495dc2...","customer_id":"c-42","sku":"sku-1","qty":2,"total_cents":2598,"currency":"EUR","price_cents":1299}گام ۲: Catalog را بکشید و باز شدن breaker را ببینید.
kill %1 # catalog
for i in 1 2 3 4; do curl -s -o /dev/null -w "req$i status=%{http_code} time=%{time_total}s\n" \
-X POST localhost:18080/orders -d '{"customer_id":"c-42","sku":"sku-1","qty":1}'; done
# req1 status=503 time=0.006297s
# req2 status=503 time=0.051295s (second try waited for jitter)
# req3 status=503 time=0.013541s (5th failed attempt: breaker opens)
# req4 status=503 time=0.000488s (no network call at all)
curl -s -i -X POST localhost:18080/orders -d '{"customer_id":"c-42","sku":"sku-1","qty":1}' | grep -E "HTTP/|Retry-After|error"
# HTTP/1.1 503 Service Unavailable
# Retry-After: 10
# {"breaker":"open","error":"catalog_unavailable"}انتظار: Orders بالا میماند و در چند میلیثانیه جواب میدهد؛ /readyz در Orders همچنان 200 است (Catalog را بررسی نمیکند). لاگ Orders: "msg":"catalog call failed",...,"err":"... connect: connection refused".
گام ۳: وابستگی کند. Catalog را با SLOW_MS=1000 دوباره راه بیندازید، 10 ثانیه برای خنکشدن صبر کنید، دوباره سفارش بدهید:
slow status=503 time=0.315355sانتظار: یک فراخوانی آزمایشی (half-open) به timeout 300 ms هر تلاش میخورد (context deadline exceeded)، breaker دوباره باز میشود، breaker باز retry را رد میکند، و کاربر بهجای 1 ثانیه یا تا ابد، 0.3 ثانیه منتظر میماند.
گام ۴: بازیابی. Catalog را بدون SLOW_MS راه بیندازید، 10 ثانیه صبر کنید، سفارش بدهید: recovered status=201 time=0.001940s. فراخوانی آزمایشی موفق شد و breaker را بست.
گام ۵: Notifications پایین، سفارشها همچنان موفق. Notifications را متوقف کنید، سفارش بدهید (status=201)، ببینید Orders هر ثانیه "msg":"relay: will retry","event_id":"902d0a14..." لاگ میکند، Notifications را دوباره بالا بیاورید: event تحویل میشود ("msg":"email queued"). سفارش هیچوقت به Notifications وابسته نبود.
گام ۶: یک trace در سه سرویس.
T=$(grep '"correlation_id":"lab-1"' orders.log | sed 's/.*"trace_id":"\([0-9a-f]*\)".*/\1/')
grep -l "$T" *.log
# catalog.log
# notif.log
# orders.logهمان trace_id (در اجرای ما 9fff831ec7a41f395523bcd8893c6424) در لاگ درخواست Orders، لاگ درخواست Catalog و یک ثانیه بعد در خط email queued در Notifications دیده میشود، چون relay، traceparent ذخیرهشده همراه event در outbox را برگرداند. با docker compose، Jaeger را باز کنید و سرویس orders را جستوجو کنید تا spanها را مثل نمودار trace ببینید.
| سنجه | مشاهده | چرا |
|---|---|---|
| زمان شکست با Catalog پایین، breaker بسته | 6 تا 51 ms | connection refused سریع است؛ jitter روی retry |
| زمان شکست با breaker باز | 0.5 ms | بدون فراخوانی شبکه |
| زمان شکست با Catalog کند | 315 ms | timeout 300 ms هر تلاش، بعد breaker باز retry را رد میکند |
| دسترسپذیری Orders وقتی Notifications پایین است | 100% (201) | async از مسیر outbox |
| سرویسهایی که یک trace مشترک دارند | 3 از 3 | traceparent روی HTTP و از مسیر outbox |
گام ۷ (Laravel، اختیاری). در یک برنامهٔ Laravel 13 با Octane و Sanctum (php artisan install:api و HasApiTokens روی مدل User)، فایلهای PHP را کپی کنید، migration را اجرا کنید، با php artisan billing:issue-token orders --ability=charges:create توکن صادر کنید و ./vendor/bin/pest tests/Feature/ChargeContractTest.php را اجرا کنید. انتظار: سه تست پاس (ایجاد شد، تکرار idempotent جواب 200 میدهد، نبود ability جواب 403 میدهد).
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| میکروسرویس یعنی سرویس کوچک | اندازه خیلی متغیر است؛ آزمون، استقرارپذیری مستقل و مالکیت واحد است |
| Containerها یا Kubernetes آن را میکروسرویس میکنند | بستهبندی و زمانبندیاند؛ مرزها و مالکیت داده تصمیمهای جداییاند |
| میکروسرویس سریعتر است | هر پرش تأخیر و شکست اضافه میکند؛ تیمها و بار نامتوازن را scale میکند |
| برای continuous delivery میکروسرویس لازم است | Fowler از Facebook و Etsy نام میبرد که با monolith این کار را میکنند |
| database per service یعنی یک سرور برای هر سرویس | جدولهای خصوصی یا schema خصوصی هم قبول است (microservices.io) |
| تراکنش توزیعشده (2PC) نوشتن بین سرویسها را حل میکند | "notoriously difficult"؛ از saga، outbox و جبران استفاده کنید |
| کتابخانههای دامنهٔ مشترک وقت را صرفهجویی میکنند | انتشارها را به هم گره میزنند: distributed monolith |
| تست end-to-end تور ایمنی اصلی است | کند و شکننده است؛ از component و contract test استفاده کنید، E2E کم |
| سرویس بیشتر یعنی استقلال بیشتر | بعد از نقطهٔ تعادل نیروهای تجمیع، به nanoserviceهای پرحرف میرسید |
| Readiness باید همهٔ وابستگیها را بررسی کند | بررسی سرویسهای پاییندست یک قطعی را به همهٔ فراخوانندهها سرایت میدهد |
| Retry فراخوانی را قابلاعتماد میکند | retry نامحدود قطعی را تشدید میکند؛ محدودش کنید، jitter بدهید، فقط idempotent |
| Prime Video ثابت کرد میکروسرویس غلط است | نشان داد یک بار کاری بهشکل یک پردازه بهتر بود؛ درسش توجیه توزیع است |
| میکروسرویس و SOA ربطی به هم ندارند | Lewis و Fowler: بعضی میکروسرویس را "service orientation done right" میدانند؛ ESB تفاوت اصلی است |
چکیده
| موضوع | به خاطر بسپارید |
|---|---|
| تعریف | مجموعهای از سرویسهای کوچک، پردازهٔ خودشان، ارتباط سبک، قابلیتهای کسبوکار، استقرار مستقل (Lewis و Fowler ۲۰۱۴) |
| نُه ویژگی | سرویس بهعنوان مؤلفه، قابلیت کسبوکار، محصول، endpoint هوشمند، حاکمیت و دادهٔ غیرمتمرکز، خودکارسازی، طراحی برای شکست، طراحی تکاملی |
| آزمون واقعی | آیا این سرویس امروز، تنها، منتشر میشود؟ |
| دانهبندی | 6 نیروی تجزیه (دامنه، ناپایداری کد، مقیاس، تحمل خطا، امنیت، توسعهپذیری) در برابر 4 نیروی تجمیع (تراکنش، workflow، کد مشترک، رابطهٔ داده) |
| تیمها | یک مالک برای هر سرویس؛ اندازهٔ two-pizza؛ تیمهای stream-aligned بهعلاوهٔ platform team |
| حق بیمه | استقرار، پایش، مدیریت شکست، eventual consistency: فقط بالای آستانهٔ پیچیدگی بپردازید |
| پیشنیازها | تأمین سریع، پایش، استقرار سریع، فرهنگ DevOps؛ بعد tracing و CD کامل |
| دغدغههای مشترک | کتابخانهٔ chassis یا sidecar/mesh: auth، لاگ، trace، متریک، health، config، secret |
| داده | خصوصی برای هر سرویس؛ saga، outbox، inbox، مدل خواندنی CQRS |
| فراخوانی | sync فقط وقتی جواب همین حالا لازم است؛ یک فراخوانی sync در هر درخواست هدف خوبی است |
| تابآوری | timeout برای هر فراخوانی، retry محدود با jitter برای idempotentها، breaker، bulkhead، fallback |
| Observability | OpenTelemetry، traceparent استاندارد W3C، correlation ID در هر لاگ، متریکهای RED و کسبوکار |
| تست | unit، component، consumer-driven contract برای هر یکپارچگی، E2E خیلی کم |
| استقرار | image برای هر سرویس، rolling/blue-green/canary، liveness در برابر readiness |
| نسخهبندی | tolerant reader، تغییر افزایشی، expand-and-contract؛ نسخه بهعنوان آخرین چاره |
| ضدالگوها | distributed monolith، دیتابیس مشترک، chatty، nanoservice، entity service، envy |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — تعریف Lewis و Fowler را در یک جمله بگویید و خاصیتی را که بر آن تکیه دارد نام ببرید. حیاتی
پاسخ
پاسخ: "A suite of small services, each running in its own process and communicating with lightweight mechanisms"، ساختهشده حول قابلیتهای کسبوکار و "independently deployable by fully automated deployment machinery". خاصیت پایه استقرارپذیری مستقل است (مؤلفه "independently replaceable and upgradeable" است). تعریف را ببینید.
۲ — ده سرویس یک schema مشترک PostgreSQL دارند و هر دو هفته یک بار سهشنبه با هم منتشر میشوند. میکروسرویساند؟ حیاتی
پاسخ
پاسخ: نه: یک distributed monolithاند. مدیریت دادهٔ غیرمتمرکز و استقرارپذیری مستقل غایباند. ضدالگوها را ببینید.
۳ — سه نیروی تجزیه و سه نیروی تجمیع نام ببرید. تکمیلی
پاسخ
پاسخ: تجزیه: service scope and function، code volatility، scalability and throughput، fault tolerance، security، extensibility. تجمیع: database transactions، workflow and choreography، shared code، data relationships. دانهبندی را ببینید.
۴ — پیشنیازهای میکروسرویس از نظر Fowler کداماند؟ مهم
پاسخ
پاسخ: تأمین سریع، پایش پایه، استقرار سریع برنامه و فرهنگ DevOps؛ پس از چند سرویس اول، ردگیری تراکنشهای کسبوکاری و continuous delivery کامل. حق بیمه را ببینید.
۵ — چرا readiness probe در Orders نباید Catalog را بررسی کند؟ حیاتی
پاسخ
پاسخ: اگر Catalog پایین برود، همهٔ podهای Orders unready میشوند و Orders کامل ناپدید میشود، در حالی که هنوز میتوانست جواب بدهد (شکست سریع، سرو کردن endpointهای دیگر). readiness فقط وابستگیهایی را بررسی میکند که مال خود سرویساند. گام ۲ آزمایشگاه را ببینید.
۶ — در آزمایشگاه چرا درخواست چهارم در 0.5 ms شکست خورد؟ مهم
پاسخ
پاسخ: breaker پس از پنج تلاش ناموفق باز شده بود؛ بدون فراخوانی شبکه ErrOpen برگرداند و کلاینت آن را دائمی حساب کرد (بدون retry). تابآوری را ببینید.
۷ — trace چطور از پرش ناهمزمان به Notifications جان سالم به در میبرد؟ مهم
پاسخ
پاسخ: handler سفارش context جاری را در یک map (همان traceparent استاندارد W3C) تزریق میکند که همراه event در outbox ذخیره میشود؛ relay پیش از ارسال آن را استخراج میکند و otelhttp آن را روی درخواست خروجی میگذارد. Observability را ببینید.
۸ — consumer-driven contract چیست و کجا اجرا میشود؟ حیاتی
پاسخ
پاسخ: مصرفکننده انتظاراتش را مینویسد (درخواست و فیلدهایی که میخواند)؛ pipeline تأمینکننده آنها را روی handler واقعی دوباره اجرا میکند، پس تغییر شکننده در CI تأمینکننده شکست میخورد. تست و contract_test.go را ببینید.
۹ — Billing میخواهد amount_cents را به amount تغییر نام دهد. چطور بدون انتشار همزمان منتشرش کنید؟ حیاتی
پاسخ
پاسخ: Expand: هر دو فیلد را برگردانید؛ مصرفکنندهها را مهاجرت دهید (contract testها نشان میدهند چه کسی amount_cents را میخواند)؛ contract: وقتی هیچ قراردادی فیلد قدیمی را نمیخواند حذفش کنید. نسخهبندی را ببینید.
۱۰ — پست Prime Video و مقالهٔ HotOS گوگل چه وجه مشترکی دارند؟ تکمیلی
پاسخ
پاسخ: هر دو میگویند توزیع فیزیکی هزینهای است که باید توجیه شود: Prime Video یک بار کاری را به یک پردازه برد (به گزارش InfoQ ۹۰٪ ارزانتر)؛ گوگل استدلال میکند که میکروسرویسها "conflate logical boundaries ... with physical boundaries". هیچکدام مرز سرویس را بهخودیخود رد نمیکنند. از کجا آمده را ببینید.
۱۱ — چرا PaymentProvider::capture فقط روی ConnectionException retry میکند و همیشه همان Idempotency-Key را میفرستد؟ حیاتی
پاسخ
پاسخ: capture ذاتاً idempotent نیست: retry بعد از یک 5xx میتواند دو بار پول بکشد، مگر اینکه درگاه با کلید تکراریها را حذف کند. شکست اتصال پیش از دریافت پاسخ حالت امن retry است، و کلید ثابت حتی همان را هم امن میکند. Laravel را ببینید.
واژهنامه
| واژه | معنا |
|---|---|
| معماری میکروسرویس (Microservice architecture) | یک برنامه بهشکل مجموعهای از سرویسهای کوچک، مستقلالاستقرار و ساختهشده حول قابلیتهای کسبوکار |
| استقرارپذیری مستقل (Independent deployability) | سرویس بدون انتشار هماهنگ دیگران، تنها منتشر میشود |
| مؤلفهسازی با سرویس (Componentization via services) | مؤلفهها سرویسهای بیرون از پردازهاند، نه کتابخانهٔ درون پردازه |
| قابلیت کسبوکار (Business capability) | کاری که کسبوکار انجام میدهد (صورتحساب، کاتالوگ)، بهعنوان واحد تجزیه |
| محصول، نه پروژه (Products not projects) | تیم در تمام عمر سرویس مالکش است («you build, you run it») |
| Smart endpoints and dumb pipes | منطق در سرویسها؛ انتقال (HTTP، broker ساده) فقط پیام جابهجا میکند |
| ESB | Enterprise Service Bus: middleware دوران SOA با مسیریابی، تبدیل و قواعد کسبوکار |
| SOA | معماری سرویسگرا؛ میکروسرویس را اغلب شکل ریزدانهٔ آن میدانند |
| حاکمیت غیرمتمرکز (Decentralized governance) | تیمها برای هر سرویس ابزار انتخاب میکنند؛ استانداردها از کد کارکرده میآیند |
| مدیریت دادهٔ غیرمتمرکز (Decentralized data management) | هر سرویس مالک دادهٔ خودش است؛ schema مشترک نیست |
| Polyglot Persistence | سرویسهای مختلف با فناوریهای دیتابیس متفاوت |
| خودکارسازی زیرساخت (Infrastructure automation) | pipeline برای build، تست، تأمین و استقرار |
| طراحی برای شکست (Design for failure) | هر فراخوانی راه دور را شکستپذیر بدان؛ timeout، breaker، پایش |
| طراحی تکاملی (Evolutionary design) | انتظار شکستن، ادغام و جایگزینی سرویسها با رشد فهم |
| نیروی تجزیه (Granularity disintegrator) | نیرویی به سمت شکستن سرویس (Richards و Ford) |
| نیروی تجمیع (Granularity integrator) | نیرویی به سمت کنار هم نگه داشتن یا دوباره کنار هم گذاشتن سرویسها |
| قانون Conway (Conway's Law) | ساختار سیستم از ساختار ارتباطی سازمان کپی میشود |
| Inverse Conway Maneuver | تغییر شکل تیمها برای رسیدن به معماری دلخواه |
| تیم two-pizza | تیمی آنقدر کوچک که دو پیتزا سیرش کند (Amazon) |
| تیم stream-aligned | تیمی همراستا با جریان کار یک بخش از دامنهٔ کسبوکار (Team Topologies) |
| Platform team | فراهمکنندهٔ یک محصول داخلی (جادهٔ هموار) برای تیمهای stream-aligned |
| حق بیمهٔ میکروسرویس (Microservice premium) | هزینه و ریسک اضافهٔ اجرای یک سیستم توزیعشده |
| Monolith First | توصیهٔ Fowler: با monolith شروع کن و بعداً بشکن |
| Microservice chassis | کتابخانه یا frameworkای که دغدغههای مشترک را در هر سرویس انجام میدهد |
| Sidecar | پردازه یا container کمکی کنار هر نمونهٔ سرویس |
| Service mesh | لایهٔ زیرساختی (proxyهای data plane + control plane) که همهٔ ترافیک سرویسها را میانجیگری میکند |
| API gateway | نقطهٔ ورود واحد که برای کلاینتها مسیر میدهد، احراز هویت و ترکیب میکند |
| Service discovery | پیدا کردن آدرس شبکهٔ نمونههای سرویس |
| Database per service | دادهٔ ماندگار خصوصی برای هر سرویس، فقط از راه API آن |
| Saga | توالی هماهنگ و قابلاعتماد از تراکنشهای محلی همراه جبران |
| Transactional outbox | نوشتن event در همان تراکنش محلی داده، و ارسال بعدی آن |
| Inbox / مصرفکنندهٔ idempotent | جدول حذف تکراری تا پیام دوبارهرسیده یک بار پردازش شود |
| CQRS | جدا کردن مدل خواندن از مدل نوشتن؛ برای queryهای بین سرویسها |
| Eventual consistency | replicaها یا سرویسها بهمرور، نه آنی، همگرا میشوند |
| Circuit breaker | صدا زدن وابستگی خراب را برای مدتی متوقف میکند، بعد آزمایش میکند |
| Bulkhead | استخرهای منبع جدا تا یک وابستگی همه را مصرف نکند |
| Jitter | تصادفی کردن backoff برای جلوگیری از retryهای همزمان |
| Idempotency key | کلیدی که کلاینت انتخاب میکند تا سرور درخواستهای تکراری را حذف کند |
| OpenTelemetry | APIها، SDKها و پروتکل (OTLP) بیطرف برای trace، متریک و لاگ |
| traceparent | header استاندارد W3C Trace Context با trace ID، parent span ID و flags |
| Correlation ID | شناسهٔ درخواست در سطح کسبوکار که هر سرویس مسیر لاگش میکند |
| پایش معنایی (Semantic monitoring) | پایش نتیجههای کسبوکاری، نه فقط متریکهای فنی |
| Liveness / readiness / startup probe | بررسیهای Kubernetes: ریاستارت، ارسال ترافیک، صبر برای شروع |
| Rolling update | جایگزینی تدریجی نمونهها (maxUnavailable، maxSurge) |
| Blue/green deployment | دو محیط یکسان؛ ترافیک را عوض کن؛ برای برگشت دوباره عوض کن |
| Canary release | سهم کوچکی از کاربران اول به نسخهٔ تازه میروند |
| Contract test | سنجش یک یکپارچگی در برابر قراردادی مشترک، هر طرف جداگانه |
| Consumer-driven contract | قراردادی که مصرفکننده مینویسد و pipeline تأمینکننده آن را میسنجد (Pact) |
| Component test | تست یک سرویس در انزوا با همکاران جعلی |
| هرم تست (Test pyramid) | تست unit زیاد، integration/component/contract کمتر، end-to-end خیلی کم |
| Tolerant Reader | مصرفکننده فقط آنچه لازم دارد را میخواند و دادهٔ ناشناخته را نادیده میگیرد |
| Expand and contract | شکل تازه را اضافه کن، کاربران را مهاجرت بده، شکل قدیم را حذف کن |
| Distributed monolith | سرویسهایی که نمیشود مستقل مستقرشان کرد |
| Nanoservice | سرویسی آنقدر کوچک که سربارش از ارزشش بیشتر است |
| Entity service | سرویس CRUD برای هر اسم داده؛ ضدالگوی تجزیه |
| Strangler fig | جایگزینی تدریجی یک سیستم قدیمی از لبههایش |
| DOMA | معماری میکروسرویس دامنهمحور Uber: سرویسها در دامنهها پشت gateway |
| Logical monolith | مقالهٔ HotOS 2023 گوگل: یک برنامهٔ منطقی بنویس، بگذار runtime توزیع فیزیکی را تعیین کند |
| متریکهای DORA | change lead time، deployment frequency، failed deployment recovery time، change fail rate، deployment rework rate |
| Octane | پکیج Laravel که برنامه را از workerهای ماندگار سرو میکند (FrankenPHP، RoadRunner، Swoole) |
| Sanctum | احراز هویت سبک با توکن API و ability در Laravel |
| chi | router سبک Go و سازگار با net/http |
| gRPC | framework فراخوانی راه دور روی HTTP/2 با قرارداد Protocol Buffers (در Go: grpc-go) |
| Hystrix | کتابخانهٔ تحمل تأخیر و خطای Netflix (در حالت نگهداری) |
منابع
- James Lewis and Martin Fowler, "Microservices: a definition of this new architectural term", 25 March 2014
- Martin Fowler, "Microservice Prerequisites", 28 August 2014; "Microservice Premium", 13 May 2015; "Monolith First", 3 June 2015; "Microservice Trade-Offs", 1 July 2015
- Martin Fowler, "Circuit Breaker", 6 March 2014; "Tolerant Reader", 9 May 2011; "Blue Green Deployment", 1 March 2010; "Strangler Fig", 22 August 2024; "Contract Test"
- Danilo Sato, "Canary Release", 25 June 2014
- Toby Clemson, "Testing Strategies in a Microservice Architecture", 18 November 2014
- Sam Newman, Building Microservices, 2nd Edition (book page and chapter list)
- Neal Ford, Mark Richards, Pramod Sadalage, Zhamak Dehghani, Software Architecture: The Hard Parts, chapter 7 "Service Granularity" (free excerpt PDF, Thoughtworks)
- Chris Richardson, microservices.io: Microservice Architecture, Database per service, Saga, Microservice chassis, Sidecar, Service mesh, Distributed tracing, Service integration contract test
- Netflix, Hystrix wiki: How it works / Home and README (maintenance mode)
- Amazon, AWS whitepaper "Introduction to DevOps on AWS": Two-Pizza Teams
- Adam Gluck (Uber), "Introducing Domain-Oriented Microservice Architecture", 23 July 2020 (از طریق ابزار fetch خوانده شد؛ اعداد به همان شکل گزارششده)
- InfoQ, "Prime Video Switched from Serverless to EC2 and ECS to Save Costs", May 2023 (منبع دست دوم؛ پست اصلی Prime Video Tech اکنون redirect میشود)
- Sanjay Ghemawat et al. (Google), "Towards Modern Development of Cloud Applications", HotOS 2023
- DORA, "DORA's software delivery performance metrics"
- Team Topologies, Key concepts
- W3C, Trace Context; OpenTelemetry, Go getting started; otelhttp source
- Pact, Introduction to contract testing; Istio, Architecture
- Kubernetes, Deployments, Liveness, Readiness, and Startup Probes
- Laravel 13: Octane, HTTP Client, Sanctum, Queues, Context, Deployment (health route)
- Go: chi, grpc-go basics