Software Engineer Encyclopedia
0%
Domain 09 · System Design & Distributed Systems · Topic 9.2

Microservices والأنماط الموزعة

Microservices & Distributed Patterns

Bounded contexts, service boundaries, gateways, sync/async communication, Saga, Outbox, migration and anti-patterns.

  • Advanced
  • ~14 min read
  • 16 sections
  • 4 code examples
  • 1 diagrams
  • 7 questions
  • Priority L2 · Important
  • ASP.NET Core · .NET 8+ · SQL Server · Redis · RabbitMQ

بعد الدرس ده هتقدر

  • تبني saga بـ compensations بالترتيب العكسي وخطوات idempotent.
  • تفرّق بين الفشل المؤقت والدائم، وبين orchestration وchoreography.

المتطلبات قبل ما تبدأ

Backend + Databases + أساسيات النشر والمراقبة.

مستوى التعمق المطلوب

BASICS (CONCEPTS FIRST)Understand the trade-offs. Build a modular monolith first, then split one module to learn the costs.

01

Monolith أم Modular Monolith أم Microservices؟

Choose deployment boundaries deliberately
Deep dive

Monolith تطبيق واحد غالبًا بقاعدة واحدة ونشر واحد. ليس مرادفًا للفوضى؛ قد يكون منظمًا جدًا. Modular Monolith يحافظ على deployment واحد لكنه يفرض modules بواجهات و ownership واضحين. Microservices خدمات مستقلة deployment/data ownership ويمكن تطويرها وتوسيعها بشكل مستقل، مقابل تكلفة distributed systems.

اختَر Microservices عندما عندك bounded contexts مستقرة، فرق مستقلة، اختلاف واضح في scaling/release cadence، أو isolation/security requirements. تجنبها لو الفريق صغير، domain غير مفهوم، deployment/observability غير ناضجة، أو كل خدمة ستحتاج synchronous calls كثيرة لإتمام request واحد.

Distributed Monolith هو أسوأ مزيج: خدمات كثيرة منفصلة deployment لكن مترابطة tightly، shared database، coordinated releases، synchronous chains، وغياب ownership. عدد الخدمات لا يثبت maturity.

قاعدة عمليةابدأ Modular Monolith. افصل module إلى service فقط عندما تستطيع وصف contract وحدود بياناته وسبب استقلاله، وتستطيع تشغيله ومراقبته وتأمينه.
02

Bounded Context و Service Boundaries

Domain language should shape ownership
Deep dive

Bounded Context من DDD هو حد تكون داخله اللغة والنموذج متسقين. كلمة Customer قد تعني buyer في Sales، account holder في Billing، و recipient في Shipping. لا تفرض entity واحدة مشتركة بين كل domains. Service boundary الجيدة غالبًا تتبع business capability وليس جدولًا واحدًا.

علامات boundary سليمة: بيانات يملكها فريق/موديول واحد، business rules متماسكة، changes تتغير معًا، contract واضح، واستخدامات خارجية محدودة. علامات سيئة: service لكل CRUD table، أو service تحتاج قراءة 6 services لإنشاء order، أو shared database يجعل أي تعديل schema يتطلب تنسيقًا جماعيًا.

Database per service تعني ownership منطقيًا؛ قد تستخدم نفس database server في البداية لكن schemas/credentials/permissions منفصلة، ولا تسمح لخدمة أخرى بالكتابة مباشرة في جداولها. الوصول يكون عبر API أو events أو read model متفق عليه.

03

Synchronous vs Asynchronous Communication

HTTP/gRPC calls versus messages and events
Deep dive

HTTP/REST مناسب لطلب/استجابة واضحة وقراءة/أمر يحتاج نتيجة فورية. gRPC مفيد للـ service-to-service typed contracts و streaming و low overhead. Messaging مناسب لفصل الزمن والـ availability، buffering، fan-out، و workflows لا تحتاج response فوريًا.

كل synchronous hop يضيف latency و failure dependency. لو Checkout ينادي Inventory ثم Pricing ثم Promotions ثم Shipping، توافر العملية يتأثر بسلسلة dependencies. ضع timeout لكل call، deadline end-to-end، bulkhead، fallback عند وجوده، و trace context. لا تعمل fallback يخترع نجاحًا ماليًا.

Async communication يزيل coupling الزمني لكنه يضيف eventual consistency، duplicate delivery، ordering questions، retries، DLQ، schema evolution، و eventual observability. لا تعتبر queue حلًا سحريًا؛ هي تنقل التعقيد إلى workflow.

SynchronousCheckoutInventoryPricingEvery hop affects response latency and availabilityAsynchronousCheckoutBrokerConsumerEventually
Synchronous request chain versus asynchronous event handoff
04

API Gateway و BFF و YARP

Route, aggregate and protect at the edge
Practical

API Gateway نقطة دخول موحدة للـ clients: routing، TLS termination، authentication integration، rate limiting، request size limits، correlation IDs، وربما aggregation. لا تضع business logic ثقيلًا أو قواعد domain فيه؛ وإلا يتحول إلى central bottleneck.

BFF Backend for Frontend يقدم API مناسبة لكل client: mobile يحتاج payload مختصرًا، web يحتاج بيانات مختلفة. لا تنشئ BFF لكل شاشة؛ اجعلها thin composition layer. YARP reverse proxy من Microsoft ecosystem يمكن استخدامه لبناء gateway في ‎.NET، مع health/load balancing/transforms حسب الإعداد.

C#YARP route and cluster configuration
// appsettings.json
{
  "ReverseProxy": {
    "Routes": {
      "catalog-route": {
        "ClusterId": "catalog",
        "Match": { "Path": "/catalog/{**catch-all}" }
      }
    },
    "Clusters": {
      "catalog": {
        "Destinations": {
          "primary": { "Address": "https://catalog-api/" }
        }
      }
    }
  }
}

// Program.cs
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
app.MapReverseProxy();

أمّن forwarded headers: لا تثق بأي X-Forwarded-* من client مباشرة؛ حدد known proxies/networks. ضع limits للـ body/timeouts، وراقب gateway latency منفصلة عن downstream. Gateway لا يلغي authz داخل كل service؛ كل service تتحقق من authorization على resource الذي تملكه.

05

Saga و Distributed Transactions

Coordinate business workflows without one global DB transaction
Deep dive

لا يمكنك عادة فتح ACID transaction واحدة تشمل قواعد بيانات مستقلة وخدمات HTTP وبروكر بطريقة بسيطة وآمنة. Saga تقسم workflow إلى local transactions، ولكل خطوة قد توجد compensating action. مثال Order: Reserve Inventory → Authorize Payment → Arrange Shipment. لو الدفع فشل، release inventory.

Orchestration: Saga coordinator يقرر الخطوة التالية ويتابع state؛ أسهل في تتبع workflow المعقد لكنه يضيف orchestrator. Choreography: services تتفاعل عبر events دون coordinator مركزي؛ أقل مركزية لكنه قد يصنع event spaghetti وصعوبة فهم overall state.

Compensation ليست rollback حقيقيًا دائمًا. Refund لا يمحو charge الذي حدث؛ هو business action جديدة وقد يفشل أو يحتاج تدخلًا. صمم Saga state machine، timeout لكل step، retries idempotent، manual intervention، audit trail، و terminal states واضحة.

TextOrder Saga state transitions
Pending
  -> InventoryReserved
  -> PaymentAuthorized
  -> ShipmentRequested
  -> Completed

Failure branches:
InventoryReserved + PaymentFailed -> ReleaseInventory -> Failed
PaymentAuthorized + ShipmentFailed -> VoidOrRefundPayment -> ReleaseInventory -> Compensated

Every command has a stable operation ID.
Every transition is persisted before publishing the next event.

اختبر crash بعد كل خطوة، duplicate event، compensation failure، delayed event، و out-of-order delivery. لا تكتفِ باختبار happy path.

06

Outbox و Inbox و Reliable Event Publication

Solve the database/broker dual-write gap
Deep dive

المشكلة: transaction تحفظ Order في DB، ثم publish event إلى broker. لو DB commit نجح و broker publish فشل، النظام يرى order بدون event. ولو publish نجح و DB rollback، consumer يرى حدثًا لعملية غير موجودة. ده dual-write problem.

Transactional Outbox: احفظ business change و OutboxMessage في نفس DB transaction. Background publisher يقرأ pending rows ويرسلها ثم يعلّمها published. قد يرسل duplicate لو نشر ثم crash قبل تحديث status؛ لذلك consumer لازم idempotent. Outbox يضمن atomic persistence داخل database، وليس exactly-once delivery عبر كل الشبكة.

C#Write business state and outbox atomically
await using var tx = await db.Database.BeginTransactionAsync(ct);

var order = Order.Create(customerId);
db.Orders.Add(order);
db.OutboxMessages.Add(new OutboxMessage
{
    Id = Guid.NewGuid(),
    Type = "OrderPlaced.v1",
    Payload = JsonSerializer.Serialize(new OrderPlaced(order.Id, order.CustomerId)),
    OccurredAtUtc = clock.UtcNow
});

await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);

Publisher يجب أن يملك lease/locking مناسبًا لو عندك عدة replicas، ويستخدم bounded batches، retry/backoff، poison handling، metrics للـ oldest pending age. Inbox يسجل message IDs التي عالجها consumer في نفس transaction مع business state؛ unique constraint يمنع duplicate effects.

07

Strangler Fig و Anti-Corruption Layer

Evolve a legacy monolith incrementally
Practical

Strangler Fig migration تنقل capability واحدة في كل مرة: ضع routing seam، ابدأ بقراءة أو write path محدد، انقل business behavior/data ownership، راقب parity، ثم أزل القديم. لا تبدأ rewrite شاملًا قبل فهم behavior الفعلي والـ edge cases.

Anti-Corruption Layer يحول legacy model إلى model داخلي نظيف. لا تسمح أن تنتشر أسماء/quirks النظام القديم داخل new domain. ACL قد تكون adapter/translator في integration boundary. ضع contract tests و shadow reads أو reconciliation حيث يكون ذلك آمنًا.

Migration plan يحتاج rollback: feature flag، routing switch، data sync/dual-read policy، backfill، reconciliation، monitoring، و cutover criteria. Dual-write إلى النظامين خطير ما لم توجد استراتيجية conflict/recovery واضحة.

08

Service Discovery و Configuration و Secrets

Find services safely and keep runtime config controlled
Basics

في بيئة dynamic، IPs تتغير؛ استخدم stable DNS/service names أو platform service discovery. Kubernetes Service يوفر stable virtual endpoint داخل cluster. لا تخزن IP ثابتًا في code. Configuration per environment، secrets في secret manager، و rotation دون rebuild متى أمكن.

كل service تحتاج identity خاصة بها، least-privilege access، network policy، TLS/mTLS عند الحاجة، resource limits، health probes، graceful shutdown، structured logs، trace propagation. لا تضع broker/database credentials في config file committed to Git.

Service mesh قد يوفر mTLS/traffic policy/retries/telemetry على مستوى infrastructure، لكنه يضيف control plane/data plane complexity. لا تضفه لمجرد أن architecture diagram تبدو enterprise.

09

متى لا تستخدم Microservices؟

A practical decision checklist
Deep dive

لا تستخدمها لو ما زلت تغيّر domain boundaries يوميًا، الفريق 2–4 developers، الـ deployments غير مؤتمتة، لا توجد tracing/alerts، كل الخدمات ستشارك database، أو كل request يحتاج synchronous chain. modular monolith يسمح باكتشاف boundaries قبل دفع تكلفة الشبكة.

استخدم extraction checklist: (1) capability مستقرة، (2) owner واضح، (3) data ownership مستقل، (4) contract versioned، (5) independent deploy/test، (6) observability/security جاهزة، (7) failure mode وخطة rollback، (8) benefit measurable. لو لم تستطع الإجابة، أجّل الفصل.

10

Service Contracts و API Evolution

Version contracts without coordinated deployments
Deep dive

Contract-first design يبدأ من consumer needs: operations، payloads، error semantics، idempotency، pagination، auth scopes، timeout expectations. OpenAPI/Protobuf schemas تساعد، لكنها لا تضمن compatibility وحدها. Consumer-driven contract tests تكشف assumptions التي لا تظهر في schema.

Prefer additive evolution: إضافة optional field، إضافة endpoint، دعم old/new versions خلال migration. تجنب rename/remove/type change دون deprecation window. Producers لا يجب أن يفترضوا أن كل consumers deployوا في نفس اللحظة. Events تحتاج schema compatibility policy، APIs تحتاج versioning/deprecation policy.

لا تستخدم version في كل route تلقائيًا. Version only breaking contracts. Feature flags أو expand-contract database migration تسمح بنشر مرحلي: add new column, dual-read/temporary dual-write if safe, backfill, switch readers, remove old column later.

11

Data Ownership و Cross-Service Queries

Avoid shared database coupling
Deep dive

الخدمة المالكة للبيانات وحدها تكتبها وتفرض invariants. لو Shipping تحتاج Customer address، قد تستقبل snapshot عند order placement أو تستعلم Customer API حسب freshness needs. Snapshot يحفظ historical truth (العنوان وقت الطلب)، بينما live lookup يعرض current state؛ القرار business وليس database convenience.

Cross-service joins لا تعملها عبر database credentials مشتركة. خيارات القراءة: API composition (بسيط لكن latency/coupling)، materialized read model (eventually consistent)، data warehouse/analytics pipeline (تحليلات)، أو denormalized snapshot داخل aggregate. حدد freshness و reconciliation لكل اختيار.

Schema-per-service على نفس SQL Server قد يكون مرحلة انتقالية، لكن permissions يجب أن تمنع direct cross-schema writes. لا تستخدم foreign key بين databases مستقلة باعتبارها service boundary؛ ownership يجب أن يبقى واضحًا.

12

Deployment Patterns و Release Independence

Can services really ship independently?
Practical

Independent deployability تحتاج backward-compatible contracts، automated tests، database migrations expand/contract، configuration versioning، feature flags، health/readiness، و rollback plan. لو deploy خدمة A يتطلب deploy B في نفس الدقيقة، لديك coupling حتى لو repositories منفصلة.

Canary يرسل نسبة صغيرة من traffic إلى version جديد ويقارن error/latency/business metrics. Blue-green يشغل بيئتين ويحوّل traffic، لكنه يحتاج data/schema compatibility. Rolling deployment يحدّث instances تدريجيًا ويحتاج N-1 compatibility أثناء overlap. لا تعتمد على rollback code لو schema migration destructive.

Service ownership يتضمن on-call، dashboard، SLO، runbook، dependency map، cost، security patching، و incident responsibility. Microservices ليست مجرد تقسيم source code؛ هي تقسيم مسؤولية تشغيلية.

13

Distributed Monolith: علامات الخطر

Networked components without real autonomy
Pitfalls

علاماته: synchronous call chains طويلة، shared DB، coordinated releases، shared domain library ضخمة، distributed transactions متكررة، team ownership غير واضح، وكل service لا تعمل وحدها. النتيجة latency أعلى وفشل أكثر دون استقلالية حقيقية.

العلاج ليس إعادة كتابة فورية. قلل synchronous edges، عرّف data ownership، اجمع services التي تتغير معًا داخل module واحد، حوّل workflows إلى events عند قبول eventual consistency، وأضف tracing حتى ترى coupling الفعلي. أحيانًا دمج خدمتين هو تحسين architecture وليس تراجعًا.

14

Saga بالكود: فشل في النص، و Compensation بترجّع النظام

An orchestrated saga with compensations, retries and failure injection — executed
Deep dive

في monolith، «اخصم الفلوس واحجز المخزون واعمل الشحنة» transaction واحدة: يا تنجح كلها يا تفشل كلها. لما كل خطوة بقت في خدمة بقاعدة بياناتها، الضمان ده اختفى. الـ saga بتستبدله بضمان أضعف لكنه ممكن: كل خطوة ليها compensation، ولو خطوة فشلت بننفّذ عكس كل اللي نجح قبلها — بالترتيب العكسي.

Pythonsaga.py — orchestrator, idempotent steps, compensation in reverse order, every failure point exercisedExecuted ✓
class StepFailed(Exception): pass

class World:
    """Three 'services', each with its own state. Every operation is idempotent by saga id."""
    def __init__(self, fail_at=None, flaky=None):
        self.balance, self.stock, self.shipments = 500, 3, {}
        self.charges, self.reservations = {}, {}
        self.fail_at, self.flaky, self.log = fail_at, dict(flaky or {}), []

    def _maybe_fail(self, name):
        if self.flaky.get(name, 0) > 0:                 # transient error: succeeds after N tries
            self.flaky[name] -= 1; raise StepFailed(f"{name}: timeout")
        if self.fail_at == name:
            raise StepFailed(f"{name}: rejected")       # permanent business failure

    def charge(self, sid, amount):
        if sid in self.charges: return                  # idempotent: a retry must not charge twice
        self._maybe_fail("charge")
        if self.balance < amount: raise StepFailed("charge: insufficient funds")
        self.balance -= amount; self.charges[sid] = amount
    def refund(self, sid):
        amount = self.charges.pop(sid, None)            # idempotent: refunding twice is a no-op
        if amount: self.balance += amount

    def reserve(self, sid, qty):
        if sid in self.reservations: return
        self._maybe_fail("reserve")
        if self.stock < qty: raise StepFailed("reserve: out of stock")
        self.stock -= qty; self.reservations[sid] = qty
    def release(self, sid):
        qty = self.reservations.pop(sid, None)
        if qty: self.stock += qty

    def ship(self, sid):
        if sid in self.shipments: return
        self._maybe_fail("ship")
        self.shipments[sid] = "created"
    def cancel_shipment(self, sid):
        self.shipments.pop(sid, None)

def run_saga(w, sid, amount, qty, max_attempts=3):
    steps = [("charge",  lambda: w.charge(sid, amount), lambda: w.refund(sid)),
             ("reserve", lambda: w.reserve(sid, qty),    lambda: w.release(sid)),
             ("ship",    lambda: w.ship(sid),            lambda: w.cancel_shipment(sid))]
    done = []
    for name, action, compensate in steps:
        for attempt in range(1, max_attempts + 1):
            try:
                action(); done.append((name, compensate)); w.log.append(f"{name} ok" + (f" (attempt {attempt})" if attempt > 1 else "")); break
            except StepFailed as e:
                transient = "timeout" in str(e)
                if transient and attempt < max_attempts:
                    continue                             # retry transient failures only
                w.log.append(f"{name} FAILED: {e}")
                for cname, comp in reversed(done):       # undo what succeeded, newest first
                    comp(); w.log.append(f"compensate {cname}")
                return "compensated"
    return "completed"

def scenario(title, **kw):
    w = World(**kw)
    status = run_saga(w, "saga-1", amount=120, qty=2)
    consistent = (status == "completed") == (w.balance == 380 and w.stock == 1 and "saga-1" in w.shipments) and \
                 (status == "compensated") == (w.balance == 500 and w.stock == 3 and not w.shipments)
    print(f"{title:<34} {status:<12} balance={w.balance} stock={w.stock} shipments={len(w.shipments)}  consistent={consistent}")
    print("     " + " -> ".join(w.log))

scenario("happy path")
scenario("payment declined", fail_at="charge")
scenario("out of stock after charging", fail_at="reserve")
scenario("shipping rejects at the last step", fail_at="ship")
scenario("inventory times out twice", flaky={"reserve": 2})
scenario("inventory keeps timing out", flaky={"reserve": 5})
ConsoleOutput — captured from a real run
happy path                         completed    balance=380 stock=1 shipments=1  consistent=True
     charge ok -> reserve ok -> ship ok
payment declined                   compensated  balance=500 stock=3 shipments=0  consistent=True
     charge FAILED: charge: rejected
out of stock after charging        compensated  balance=500 stock=3 shipments=0  consistent=True
     charge ok -> reserve FAILED: reserve: rejected -> compensate charge
shipping rejects at the last step  compensated  balance=500 stock=3 shipments=0  consistent=True
     charge ok -> reserve ok -> ship FAILED: ship: rejected -> compensate reserve -> compensate charge
inventory times out twice          completed    balance=380 stock=1 shipments=1  consistent=True
     charge ok -> reserve ok (attempt 3) -> ship ok
inventory keeps timing out         compensated  balance=500 stock=3 shipments=0  consistent=True
     charge ok -> reserve FAILED: reserve: timeout -> compensate charge

كل سيناريو انتهى في واحدة من حالتين بس: كله اتنفذ، أو كله رجع زي ما كان (consistent=True في الستة). ده معنى الـ saga: مفيش حالة «الفلوس اتخصمت والبضاعة ما اتحجزتش» تفضل للأبد.

الترتيب العكسي: لما الشحن فشل، اتلغى الحجز الأول وبعدين اترد المبلغ. والـ retry على الـ timeout بس: «رصيد غير كافي» مش هيتغير لو أعدت المحاولة، لكن timeout ممكن يعدّي.

الـ idempotency هو اللي بيخلي ده آمن: timeout معناه «مش عارف هل اتنفذ ولا لأ». إعادة charge بنفس الـ saga id ما بتخصمش مرتين، وإعادة refund ما بتردّش مرتين. من غير ده، الـ retries والـ compensations نفسها بتبقى مصدر عدم اتساق.

اللي المحاكاة مش بتورّيه: بين الخطوات النظام في حالة وسيطة مرئية (الفلوس مخصومة والطلب لسه ما اتأكدش) — مفيش isolation. و compensation ممكن تفشل هي كمان، فلازم تتعاد لحد ما تنجح أو تتصعّد لإنسان. وبعض الأفعال مالهاش عكس حقيقي (إيميل اتبعت) — دي بتتحط آخر خطوة. والـ orchestrator نفسه لازم يحفظ حالته (شوف درس الـ durable workflows).

OrchestrationChoreography
مين بيقرر الخطوة الجايةمنسّق مركزي (زي الكود فوق)كل خدمة بتسمع events وتتصرف
وضوح الـ flowمكتوب في مكان واحدمتوزع — لازم تتبّع الـ events عشان تفهمه
الـ couplingالمنسّق يعرف كل الخدماتأقل، لكن فيه coupling خفي على شكل الـ events
مناسب لـflows فيها شروط وخطوات كتيرflows بسيطة: 2–3 خطوات خطية

saga فيها: خصم ← حجز ← إيميل تأكيد ← إنشاء شحنة. الشحنة فشلت. إيه العيب في الترتيب ده؟

15

حساب الـ Availability: كل Dependency متزامنة بتاخد من الـ Nines بتاعتك

Serial chains, redundancy, and the latency budget of a call chain — executed
Deep dive
Pythonavailability.py — what a chain of synchronous calls does to uptime and to latencyExecuted ✓
import random
random.seed(4)
YEAR_MIN = 365 * 24 * 60

def downtime(a): return (1 - a) * YEAR_MIN

print("a request that must pass through N services in series, each 99.9% available:")
for n in (1, 3, 5, 10, 20):
    a = 0.999 ** n
    print(f"   {n:>2} services -> {a:.4%} available = {downtime(a) / 60:5.1f} hours of downtime per year")

print("\nredundancy: the same service behind N independent replicas (works if at least one is up):")
for single in (0.99, 0.999):
    print("   " + f"single={single:.1%}: " + "  ".join(f"{n} replicas={1 - (1 - single) ** n:.6%}" for n in (1, 2, 3)))

print("\na realistic request path:")
path = [("gateway", 0.9999, None), ("orders API (3 replicas of 99.5%)", 1 - (1 - 0.995) ** 3, None),
        ("payments provider (external)", 0.999, None), ("inventory service", 0.999, None), ("database (primary + failover)", 0.9995, None)]
total = 1.0
for name, a, _ in path:
    total *= a; print(f"   {name:<36} {a:.4%}")
print(f"   {'end to end (all synchronous)':<36} {total:.4%}  = {downtime(total) / 60:.1f} h/year")
without = total / 0.999
print(f"   if inventory is made asynchronous (queue + eventual update): {without:.4%} = {downtime(without) / 60:.1f} h/year")

# ---------- latency: per-hop timeouts must fit inside the caller's budget ----------
def chain_latency(hops, timeout=None):
    total = 0.0
    for _ in range(hops):
        t = random.lognormvariate(-3.0, 0.8)              # median ~50 ms, heavy tail
        if timeout is not None and t > timeout:
            return None                                   # this hop timed out: the request fails fast
        total += t
    return total

print("\n5-hop synchronous chain, each hop median ~50 ms with a heavy tail (20,000 requests):")
for timeout in (None, 0.5, 0.2):
    results = [chain_latency(5, timeout) for _ in range(20_000)]
    ok = sorted(r for r in results if r is not None)
    print(f"   per-hop timeout={str(timeout):<5} success={len(ok) / len(results):6.1%}  p50={ok[len(ok) // 2] * 1000:4.0f} ms  p99={ok[int(len(ok) * .99)] * 1000:5.0f} ms  max={ok[-1] * 1000:6.0f} ms")
ConsoleOutput — captured from a real run
a request that must pass through N services in series, each 99.9% available:
    1 services -> 99.9000% available =   8.8 hours of downtime per year
    3 services -> 99.7003% available =  26.3 hours of downtime per year
    5 services -> 99.5010% available =  43.7 hours of downtime per year
   10 services -> 99.0045% available =  87.2 hours of downtime per year
   20 services -> 98.0189% available = 173.5 hours of downtime per year

redundancy: the same service behind N independent replicas (works if at least one is up):
   single=99.0%: 1 replicas=99.000000%  2 replicas=99.990000%  3 replicas=99.999900%
   single=99.9%: 1 replicas=99.900000%  2 replicas=99.999900%  3 replicas=100.000000%

a realistic request path:
   gateway                              99.9900%
   orders API (3 replicas of 99.5%)     100.0000%
   payments provider (external)         99.9000%
   inventory service                    99.9000%
   database (primary + failover)        99.9500%
   end to end (all synchronous)         99.7402%  = 22.8 h/year
   if inventory is made asynchronous (queue + eventual update): 99.8401% = 14.0 h/year

5-hop synchronous chain, each hop median ~50 ms with a heavy tail (20,000 requests):
   per-hop timeout=None  success=100.0%  p50= 315 ms  p99=  841 ms  max=  1809 ms
   per-hop timeout=0.5   success= 99.0%  p50= 315 ms  p99=  751 ms  max=  1130 ms
   per-hop timeout=0.2   success= 80.7%  p50= 286 ms  p99=  543 ms  max=   749 ms

السلسلة: كل خدمة «ممتازة» بـ 99.9%، وعشرين منها في سلسلة متزامنة = نظام بيقع ساعات كتير في السنة. الـ availabilities بتتضرب في بعض. ده أقوى اعتراض هندسي على تقسيم النظام لخدمات كتير بتنادي بعض sync: كل تقسيمة بتدفع تمنها من الـ uptime.

الـ redundancy بتشتغل في الاتجاه المعاكس: replicaين من 99% بيدّوا 99.99% — بشرط إن الأعطال مستقلة. نفس الـ deploy البايظ، نفس الـ zone، نفس الـ database وراهم = عطل مشترك، والحساب ده مالوش معنى.

تحويل dependency لـ async بيشيلها من مسار الـ request: الطلب بيتقبل والـ inventory يتحدّث من queue. الـ availability بتتحسن والتمن eventual consistency — قرار product مش تقني بس.

الـ timeouts: من غير timeout أبطأ طلب أخد 1.8 ثانية — وقت بيتحجز فيه thread و connection في كل خدمة في السلسلة. timeout 500ms قصّ الـ tail بتمن 1% فشل. لكن timeout 200ms — اللي شكله «حازم» — فشّل 19% من الطلبات، لأن 200ms قريبة من الـ tail الطبيعي لكل hop ومع 5 hops الاحتمال بيتراكم. الـ timeout بيتحدد من الـ p99 المقاس للـ dependency مش من رقم مريح.

قاعدة التداخل: الـ timeout بتاع كل hop لازم يكون أصغر من اللي فوقه، وإلا الـ caller هييأس والخدمة اللي تحت لسه شغالة على طلب محدش مستنيه. الأفضل تمرير deadline واحد مع الـ request (في ‎.NET: CancellationToken) بدل timeouts مستقلة.

عندك SLA 99.95% والـ request بيعدّي sync على 6 خدمات كل واحدة 99.9%. إيه التقييم؟

16

اختبر فهم Microservices

Knowledge check
Practical
هل Database per service تعني بالضرورة database server مختلف؟
لا؛ المهم ownership والعزل المنطقي والصلاحيات. يمكن مشاركة server في البداية مع فصل schemas/permissions.
ما الفرق بين Saga و Distributed ACID transaction؟
Saga تنسق local transactions وتعويضات business، ولا تقدم rollback ذريًا عالميًا.
لماذا Outbox consumer يجب أن يكون idempotent؟
لأن publisher قد يعيد إرسال نفس الرسالة بعد crash أو timeout؛ Outbox يضمن عدم فقد الحدث عند commit لكنه لا يضمن exactly-once delivery.
ما دور BFF؟
تقديم contract مناسب لواجهة معينة وتجميع responses عند الحاجة، دون احتواء domain core.
متى modular monolith أفضل؟
عندما الحدود غير ناضجة أو الفريق صغير أو لا يوجد سبب قوي للتوزيع؛ يعطي modularity مع تشغيل أبسط.
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 20 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionMonolith vs Modular Monolith vs Microservices§01
New sectionBounded context becomes service boundary§02
New sectionDatabase per service§02
New sectionAPI Gateway / YARP§04
New sectionSync vs async service communication§03
New sectionDistributed tracing§03
New sectionSaga§05
New sectionOutbox§03
New sectionCircuit Breaker§05
New sectionRetry with exponential backoff and jitter§05
New sectionBulkhead§06
New sectionTimeouts§16
New sectionIdempotency§05
New sectionEventual consistency§16
New sectionContract-first APIs and versioning§06
New sectionStrangler Fig migration§07
New sectionAnti-Corruption Layer§02
New sectionService discovery and configuration§07
New sectionDistributed monolith anti-pattern§01
New sectionWhen NOT to use microservices§01

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس