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

أساسيات الأنظمة الموزعة والاتساق

Distributed Systems Fundamentals

Partial failures, consistency, CAP/PACELC, replication, sharding, clocks, locks, Redis internals, object storage and consensus.

  • Advanced
  • ~21 min read
  • 13 sections
  • 3 code examples
  • 1 diagrams
  • 11 questions
  • Priority L2 · Important
  • ASP.NET Core · .NET 8+ · SQL Server · Redis · RabbitMQ

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

  • تشرح ليه hash % N بيفشل وتبني hash ring بـ virtual nodes.
  • تختار N/W/R وتفسّر علاقتهم بالـ stale reads والـ availability.

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

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

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

PRACTICALتفهم إزاي البيانات بتتكرر وبتتقسم بين أكتر من سيرفر، وإيه تأثير ده على الاتساق والأداء.

01

Partial Failure و Network Reality

Networks do not provide local-call semantics
Deep dive

داخل process، function call غالبًا إما ترجع أو ترمي exception ضمن نفس runtime. عبر network، قد لا تعرف هل request وصل، هل server نفذ، هل response ضاع، أو هل الطرف الآخر ما زال يعمل. الشبكة latency متغيرة، partitions تحدث، clocks تختلف، nodes تتوقف وتعود.

لا تفترض reliable delivery أو bounded latency أو shared memory أو synchronized clocks. صمم explicit timeouts، retries، idempotency، correlation IDs، durable state، و reconciliation. Partial failure هو سبب أساسي لتعقيد distributed systems.

Failure detector لا يستطيع دائمًا التمييز بين node crashed و node slow/isolated. لذلك timeouts هي suspicion وليس proof. قرارات leader election/leases تحتاج fencing/epochs لتجنب stale owner يكتب بعد انتهاء lease.

02

Leader-follower replication و quorum

Replication and quorums
Basics
N guarantees reads see the latest acknowledged write">LeaderFollower 1Follower 2Follower 3writeasync replication → replica lag → stale reads; N=3, W=2, R=2 → overlap on at least one node
03

Consistency Models

Strong, eventual, causal and read-your-writes
Deep dive

Strong/linearizable consistency: operation تبدو كأنها حدثت لحظيًا بترتيب عالمي يحترم real-time order. مفيدة للرصيد/unique reservations لكن تكلف latency/coordination وقد تقلل availability عند partition.

Eventual consistency: لو توقفت updates، replicas ستتقارب في النهاية؛ reads قد ترى stale data. مناسبة ل likes/counters/search indexes وبعض feeds. Read-your-writes تضمن أن العميل يرى كتابته بعد نجاحها ضمن session. Causal consistency تحافظ على ترتيب cause-before-effect دون total order لكل العمليات.

Consistency ليست كلمة واحدة على مستوى التطبيق. order status قد يكون strongly consistent في write model و eventually consistent في search projection. صمم per use case: هل stale 2 seconds مقبول؟ هل المستخدم يرى تأكيده فورًا؟ هل oversell ممنوع؟

Read replicas مع lag قد تكسر read-after-write؛ route session reads إلى primary أو استخدم replication position token/wait policy. Cache invalidation قد تخلق stale reads حتى لو DB primary strongly consistent.

اختيار Consistency per Use Case

مثال e-commerce: inventory reservation تحتاج atomic conditional write لمنع oversell؛ product search index يمكن أن يتأخر ثوانٍ؛ order status UI يمكن أن يعرض Processing؛ analytics يمكن أن تتأخر دقائق؛ payment ledger يحتاج audit/strong correctness. كل data product له freshness and correctness budget.

اكتب لكل read path: source of truth، max staleness، read-your-writes requirement، fallback، conflict behavior. اكتب لكل write path: idempotency، uniqueness، transaction boundary، retry behavior، reconciliation. بهذه الطريقة يصبح consistency قرارًا محددًا بدل نقاش نظري.

04

CAP و PACELC بدون شعارات مضللة

Partition tolerance, consistency and latency trade-offs
Deep dive

CAP يصف trade-off أثناء network partition: لا يمكن لنظام موزع أن يضمن في نفس الوقت linearizable consistency و availability لكل طلب في وجود partition. Partition tolerance ليست اختيارًا عمليًا غالبًا؛ الشبكات قد تنقسم. القرار يصبح: هل نرفض/نؤخر بعض operations للحفاظ على consistency (CP behavior)، أم نسمح بردود قديمة/متعارضة لتحافظ على availability (AP behavior)؟

CAP لا يقول إن النظام دائمًا يختار C أو A فقط. خارج partition يمكن أن يقدم الاتساق وال availability. PACELC يضيف: إذا لم توجد Partition، فما trade-off بين Latency و Consistency؟ بعض الأنظمة تختار replication coordination لتقليل latency أو consistency حسب data model.

لا تصنف database كلها CP/AP بإطلاق؛ السلوك يعتمد على operation، configuration، topology، consistency level، والـ failure scenario. اقرأ guarantees الدقيقة لكل operation.

05

Replication: Leader-Follower و Multi-Leader

Copies, lag, failover and conflict resolution
Deep dive

Leader-follower: writes تذهب إلى leader، ثم تتكرر إلى followers. Sync replication تنتظر follower acknowledgment وقد تزيد latency لكنها تقلل data loss window. Async replication أسرع لكن failover قد يفقد آخر writes لم تصل إلى replica. Read replicas تقلل read load مع stale-read risk.

Failover يحتاج اختيار replica، fencing old leader، تحديث routing، وتجنب split-brain. Epoch/term/fencing token يمنع leader قديمًا من الكتابة بعد عودة الشبكة. RPO يقيس أقصى data loss مقبول، RTO زمن استعادة الخدمة؛ backups و replication وحدهما لا يكفيان من دون restore drills.

Multi-leader يسمح writes في أكثر من region/node، لكنه يحتاج conflict detection/resolution. Last-write-wins يعتمد على clocks وقد يفقد update منطقيًا؛ CRDTs مناسبة لأنواع محددة من البيانات، وليست حلًا عامًا. Choose conflict policy per domain.

Quorum و Read/Write Consistency

Quorum غالبًا يعني عدد acknowledgements كافٍ من replicas لاتخاذ قرار. في N replicas، majority = floor(N/2)+1. بعض systems تستخدم R + W > N لضمان overlap بين read quorum و write quorum، لكن هذا وحده لا يضمن linearizability؛ يعتمد على versioning، conflict resolution، replication protocol، و failure assumptions.

Quorum يزيد availability ضمن بعض failure patterns لكنه قد يرفع latency لأنك تنتظر nodes. Sloppy quorum/ hinted handoff يغير guarantees. اقرأ product-specific semantics ولا تستنتج من المعادلة وحدها.

في leader-based DB، client قد يقرأ من leader لتحقيق latest committed data، أو follower لخفض latency مع stale risk. في multi-region systems، cross-region quorum قد يجعل write latency تساوي network round trip بعيدًا.

Quorum: R + W > N بالمحاكاة

Pythonquorum.py — stale reads under different (N, W, R) with replicas that lagExecuted ✓
import random
random.seed(5)

def stale_read_rate(n, w, r, trials=20_000):
    stale = 0
    for _ in range(trials):
        acked = set(random.sample(range(n), w))        # the write is acknowledged once W replicas have it
        read_from = random.sample(range(n), r)         # the read immediately asks R replicas
        if not acked & set(read_from):                 # none of them has the new version yet
            stale += 1
    return stale / trials

print(f"{'N':>2}{'W':>3}{'R':>3}  {'R+W>N':<7}{'stale reads':>12}  {'tolerates on write':<20}{'tolerates on read'}")
for n, w, r in [(3, 1, 1), (3, 2, 1), (3, 2, 2), (3, 3, 1), (5, 3, 3), (5, 1, 1)]:
    print(f"{n:>2}{w:>3}{r:>3}  {str(r + w > n):<7}{stale_read_rate(n, w, r):>12.1%}  {str(n - w) + ' node(s) down':<20}{n - r} node(s) down")
ConsoleOutput — captured from a real run
N  W  R  R+W>N   stale reads  tolerates on write  tolerates on read
3  1  1  False         67.1%  2 node(s) down      2 node(s) down
3  2  1  False         33.2%  1 node(s) down      2 node(s) down
3  2  2  True           0.0%  1 node(s) down      1 node(s) down
3  3  1  True           0.0%  0 node(s) down      2 node(s) down
5  3  3  True           0.0%  2 node(s) down      2 node(s) down
5  1  1  False         80.1%  4 node(s) down      4 node(s) down

القاعدة: لو R + W > N، مجموعة القراءة ومجموعة الكتابة لازم يتقاطعوا في replica واحدة على الأقل، فالقراءة دايمًا بتشوف أحدث كتابة مؤكدة — الصفوف دي stale rate بتاعها 0%. لو لأ، فيه احتمال تقرأ من replicas لسه ما وصلهاش التحديث.

الـ trade-off في العمودين الأخيرين: W=3, R=1 بيدّي قراءة سريعة ومتسقة، لكن node واحد يقع = مفيش كتابة. W=2, R=2 بيتحمل node في الاتنين بـ latency أعلى شوية للقراءة. W=1, R=1 أسرع وأعلى availability وبيقبل stale reads — ده «eventual consistency» كاختيار واعي.

حدود النموذج: المحاكاة بتفترض إن القراءة بتحصل قبل ما الـ replication يكمّل، ومش بتمثّل الكتابات المتزامنة المتعارضة ولا الـ sloppy quorum. الأنظمة الحقيقية بتضيف versioning (vector clocks أو timestamps) و read repair.

N=5 وعايز تضمن إن القراءة تشوف آخر كتابة، وتتحمل وقوع nodeين في الكتابة. أنهي إعداد؟

06

Sharding و Partitioning و Consistent Hashing

Distribute data and understand hot partitions
Deep dive

Sharding يقسم records على nodes باستخدام shard key. Range sharding سهل لل range queries لكنه قد يصنع hot ranges. Hash sharding يوزع evenly غالبًا لكنه يجعل range scans أصعب. Tenant-based shard مناسب لو tenants أحجامهم متوازنة؛ tenant ضخم قد يصبح hot shard.

اختيار shard key أصعب قرار: cardinality، write distribution، query locality، growth، rebalancing، tenant isolation. لا تختار timestamp وحده لو كل writes تذهب إلى latest partition. لا تستخدم random key لو queries تحتاج lookup by customer إلا إذا عندك secondary index/routing.

Consistent hashing يقلل عدد keys التي تتحرك عند إضافة node، وغالبًا يستخدم virtual nodes لتحسين balance. لكنه لا يحل hot key؛ key واحدة شديدة النشاط ستظل hot. حلولها: split key/aggregation، caching، replication، أو queue serialization.

قبل sharding: query/index optimization، read replicas، vertical scale، partitioning، cache، archiving. Sharding يضيف distributed joins/transactions/migrations and operational complexity؛ لا تبدأ به مبكرًا.

Shard Rebalancing و Hot Partition Mitigation

إضافة shard لا تعني نقل نصف البيانات في لحظة. Rebalancing plan: create destination، copy snapshot، stream changes after snapshot، verify checksums/counts، switch routing، drain old shard، retain rollback window. تحتاج dual-read/forwarding أو routing epoch لتجنب lost writes أثناء cutover.

Hot partition detection: per-shard QPS/CPU/IOPS/queue age، per-key skew، top tenants. Mitigations: split tenant، salt keys for write distribution، cache reads، queue serialize hot aggregate، pre-aggregate counters، أو isolate whale tenant. Salting يجعل reads/aggregation أعقد.

Shard map يجب أن تكون versioned وموزعة بأمان. لو clients يحتفظون stale map، استخدم redirect/moved response أو routing layer central. لا تخلط data migration مع schema migration غير متوافقة.

Consistent Hashing بالأرقام: ليه hash % N كارثة

عندك cache موزع على 4 nodes وعايز تضيف الخامس. لو التوزيع hash(key) % N، تغيير N بيغيّر مكان أغلب المفاتيح: الـ cache كله بيبقى miss في لحظة والـ database بتاخد الضربة. الـ consistent hashing بيحرّك بس النصيب العادل (حوالي 1/N).

Pythonconsistent_hashing.py — remapped keys and load balance, measured on 100,000 keysExecuted ✓
import bisect, hashlib
from collections import Counter

def h(value):
    return int.from_bytes(hashlib.md5(value.encode()).digest()[:8], "big")

keys = [f"user:{i}" for i in range(100_000)]

# ---------- 1) naive: hash % N ----------
def modulo(nodes):
    return {k: nodes[h(k) % len(nodes)] for k in keys}

# ---------- 2) hash ring with virtual nodes ----------
class Ring:
    def __init__(self, nodes, vnodes):
        self.points = sorted((h(f"{n}#{v}"), n) for n in nodes for v in range(vnodes))
        self.hashes = [p for p, _ in self.points]
    def node_for(self, key):
        i = bisect.bisect(self.hashes, h(key)) % len(self.points)     # first point clockwise from the key
        return self.points[i][1]
    def assign(self):
        return {k: self.node_for(k) for k in keys}

four, five = ["n1", "n2", "n3", "n4"], ["n1", "n2", "n3", "n4", "n5"]

def moved(before, after):
    return sum(before[k] != after[k] for k in keys) / len(keys)

def spread(assignment):
    c = Counter(assignment.values())
    return max(c.values()) / (len(keys) / len(c))                     # 1.00 = perfectly even

print(f"{'strategy':<28}{'keys moved when adding n5':>27}{'busiest node vs average':>26}")
print(f"{'hash % N':<28}{moved(modulo(four), modulo(five)):>27.1%}{spread(modulo(five)):>26.2f}")
for vnodes in (1, 10, 200):
    a, b = Ring(four, vnodes).assign(), Ring(five, vnodes).assign()
    print(f"{'ring, ' + str(vnodes) + ' vnode(s)/node':<28}{moved(a, b):>27.1%}{spread(b):>26.2f}")
print(f"\nideal share that must move to a new 5th node: {1 / 5:.1%}")
ConsoleOutput — captured from a real run
strategy                      keys moved when adding n5   busiest node vs average
hash % N                                          79.9%                      1.00
ring, 1 vnode(s)/node                             25.5%                      1.62
ring, 10 vnode(s)/node                            17.9%                      1.86
ring, 200 vnode(s)/node                           19.4%                      1.04

ideal share that must move to a new 5th node: 20.0%

hash % N: حوالي 80% من المفاتيح اتحركت لما ضفنا node واحد. في cache ده معناه cold start كامل؛ في قاعدة بيانات sharded معناه نقل أغلب البيانات.

الـ ring: كل node ليه نقط على دايرة، والمفتاح بيروح لأول نقطة بعده في اتجاه عقارب الساعة. لما تضيف node، هو بياخد بس المفاتيح اللي بقت أقرب له — والباقي ما يتحركش.

الـ virtual nodes: بـ vnode واحد أو حتى 10 لكل node، الأقواس على الدايرة عشوائية الحجم: أشغل node شايل 1.6–1.9 ضعف المتوسط، ونسبة النقل بتتأرجح حوالين المثالي. بـ 200 vnode كل node متوزع على نقط كتير فالحمل بيتساوى (1.04) والنقل بيثبت قرب 20%. التمن: metadata أكتر و lookup أبطأ شوية.

فين بتقابله: Redis Cluster بيستخدم نسخة ثابتة (16384 hash slot متوزعين على الـ nodes)، Cassandra و DynamoDB بيستخدموا token ring بـ vnodes، والـ load balancers بتستخدمه للـ session affinity.

07

Ordering و Clocks و Distributed Locks

Wall clocks, logical clocks, leases and fencing
Deep dive

Wall clocks بين machines قد تختلف بسبب drift/NTP/network. لا تعتمد على timestamps وحدها لترتيب causality. Monotonic clock مناسب لقياس elapsed time داخل process؛ timestamps UTC للعرض/audit مع awareness أنها ليست globally ordered.

Lamport clock يحافظ على happens-before relation جزئيًا: عند event يزيد counter، وعند receive يأخذ max(local, received)+1. Vector clocks تكشف concurrency لكن metadata تكبر مع عدد nodes. معظم business systems لا تحتاج تنفيذ clock algorithm يدويًا؛ لكنها تحتاج فهم أن timestamp ليس sequence عالميًا.

Distributed lock via Redis/DB lease يحتاج TTL، renewal، owner token، و fencing token monotonically increasing. إذا انتهت lease والـ old worker استمر بسبب pause، قد يكتب بعد owner الجديد. Storage resource يجب أن يرفض stale fencing token. Lock لا يعوض unique constraints أو atomic business updates.

CRDTs و Conflict Resolution

CRDT (Conflict-free Replicated Data Type) يحدد merge rules تجعل replicas تتقارب تحت assumptions معينة. G-Counter يدعم increments محلية و merge بالـ max per replica؛ PN-Counter يدعم increments/decrements عبر counters منفصلة؛ OR-Set يدعم add/remove مع tags. مفيدة لبعض counters/sets/presence/collaborative data.

CRDT لا يحل كل business conflict. «حجز آخر مقعد» لا يمكن دمجه ك counter بلا policy؛ invariant capacity يجب أن يبقى صحيحًا. Last-write-wins بسيط لكنه قد يفقد تحديثًا بسبب clock skew. اختَر semantics من business meaning، لا من سهولة library.

Conflicts: Last-Write-Wins بيضيّع بيانات، و Vector Clocks بتكشف التعارض

لما replicaين يقبلوا كتابة على نفس المفتاح وهم مش شايفين بعض (partition، أو multi-region)، لازم حد يقرر «مين الصح» لما يتقابلوا. أسهل قرار — آخر timestamp يكسب — بيرمي تحديثات في صمت. الـ vector clock مش بيحل التعارض، لكنه بيعمل الحاجة الأهم: بيعرف إن فيه تعارض بدل ما يخبّيه.

Pythonconflicts.py — a shopping cart on two replicas: LWW vs vector clocks vs a CRDT setExecuted ✓
def lww_merge(a, b):
    """Last-write-wins: keep the value with the larger wall-clock timestamp."""
    return a if a["ts"] >= b["ts"] else b

def vc_compare(x, y):
    keys = set(x) | set(y)
    less = any(x.get(k, 0) < y.get(k, 0) for k in keys)
    more = any(x.get(k, 0) > y.get(k, 0) for k in keys)
    return "concurrent" if less and more else ("before" if less else ("after" if more else "equal"))

# ---- scenario: the cart starts as {book}. During a network partition:
#      replica A (phone)  adds "pen"   at wall-clock 10:00:05
#      replica B (laptop) adds "lamp"  at wall-clock 10:00:03  (its clock is 2 s behind — normal clock skew)
base = {"items": {"book"}}

print("1) last-write-wins on the whole value")
a = {"items": base["items"] | {"pen"}, "ts": 5}
b = {"items": base["items"] | {"lamp"}, "ts": 3}
print(f"   A={sorted(a['items'])} ts=5   B={sorted(b['items'])} ts=3   ->  merged={sorted(lww_merge(a, b)['items'])}   LOST: {sorted((a['items'] | b['items']) - lww_merge(a, b)['items'])}")

print("\n2) vector clocks: each replica counts its own writes")
va, vb = {"A": 1}, {"B": 1}                                   # both started from the same {} version
print(f"   clock A={va}  clock B={vb}  ->  relation: {vc_compare(va, vb)}")
print("   'concurrent' means neither saw the other's write: the store keeps BOTH versions (siblings) and asks the application to merge")
merged_items = a["items"] | b["items"]
merged_clock = {k: max(va.get(k, 0), vb.get(k, 0)) for k in set(va) | set(vb)}
print(f"   application merge (union) = {sorted(merged_items)} with clock {dict(sorted(merged_clock.items()))}")
later = {**merged_clock, "A": merged_clock["A"] + 1}
print(f"   a later write on A has clock {dict(sorted(later.items()))}: vs old A -> {vc_compare(later, va)}, vs old B -> {vc_compare(later, vb)}  (safely replaces both)")

print("\n3) but union cannot express a REMOVAL")
a_items, b_items = {"book", "pen"} - {"book"}, {"book", "lamp"}          # A removed 'book' while B added 'lamp'
print(f"   A removed 'book' -> {sorted(a_items)};  B -> {sorted(b_items)};  naive union = {sorted(a_items | b_items)}   <- the removed book is back")

class ORSet:
    """Observed-remove set (a CRDT): every add gets a unique tag; a remove deletes only the tags it has SEEN."""
    def __init__(self): self.adds, self.removed = set(), set()
    def add(self, item, tag): self.adds.add((item, tag))
    def remove(self, item): self.removed |= {(i, t) for i, t in self.adds if i == item}
    def merge(self, other):
        m = ORSet(); m.adds, m.removed = self.adds | other.adds, self.removed | other.removed; return m
    def value(self): return sorted({i for i, t in self.adds - self.removed})

A, B = ORSet(), ORSet()
for r in (A, B): r.add("book", "t0")                                      # shared starting state
A.add("pen", "a1"); A.remove("book")                                      # A: remove book
B.add("lamp", "b1"); B.add("book", "b2")                                  # B: re-adds book concurrently (a new tag)
print(f"   OR-Set: A={A.value()}  B={B.value()}  merged={A.merge(B).value()}  (same result in either order: {A.merge(B).value() == B.merge(A).value()})")
C, D = ORSet(), ORSet()
for r in (C, D): r.add("book", "t0")
C.remove("book"); D.add("lamp", "d1")
print(f"   OR-Set when B did NOT re-add the book: merged={C.merge(D).value()}  (the removal survives)")
ConsoleOutput — captured from a real run
1) last-write-wins on the whole value
   A=['book', 'pen'] ts=5   B=['book', 'lamp'] ts=3   ->  merged=['book', 'pen']   LOST: ['lamp']

2) vector clocks: each replica counts its own writes
   clock A={'A': 1}  clock B={'B': 1}  ->  relation: concurrent
   'concurrent' means neither saw the other's write: the store keeps BOTH versions (siblings) and asks the application to merge
   application merge (union) = ['book', 'lamp', 'pen'] with clock {'A': 1, 'B': 1}
   a later write on A has clock {'A': 2, 'B': 1}: vs old A -> after, vs old B -> after  (safely replaces both)

3) but union cannot express a REMOVAL
   A removed 'book' -> ['pen'];  B -> ['book', 'lamp'];  naive union = ['book', 'lamp', 'pen']   <- the removed book is back
   OR-Set: A=['pen']  B=['book', 'lamp']  merged=['book', 'lamp', 'pen']  (same result in either order: True)
   OR-Set when B did NOT re-add the book: merged=['lamp']  (the removal survives)

1) LWW ضيّع الـ lamp — ومن غير أي error. والأسوأ: الكتابة اللي «كسبت» اتحددت بساعات الأجهزة، وفرق ثانيتين في الـ clock skew عادي جدًا. LWW مقبول لما ضياع تحديث مش مهم (آخر ظهور، cache)، وخطر على أي حاجة بتتراكم (سلة، رصيد، قائمة).

2) Vector clock: لكل replica عدّاد. لو clock كل عدّاداته ≤ التاني يبقى «قبله» وينفع يتستبدل. لو كل واحد أكبر في خانة، يبقوا concurrent: محدش فيهم شاف التاني، والنظام بيحتفظ بالنسختين ويسيب الدمج للتطبيق. ده اللي Dynamo-style stores بتعمله.

3) الدمج نفسه مشكلة: union بسيط بيرجّع العناصر المحذوفة. الـ CRDTs أنواع بيانات مصممة بحيث الدمج دايمًا يوصل لنفس النتيجة بأي ترتيب ومن غير تنسيق. الـ OR-Set بيحل الحذف بإن كل إضافة ليها tag، والحذف بيشيل الـ tags اللي شافها بس — فإضافة متزامنة جديدة بتعيش، والحذف الحقيقي بيفضل.

القرار العملي: أغلب الأنظمة مش محتاجة ده كله — primary واحد للكتابة (single-leader) بيلغي التعارض من أساسه. المشكلة دي بتظهر لما تختار multi-leader أو leaderless عشان availability أو multi-region، وساعتها لازم تختار استراتيجية تعارض بوعي لكل نوع بيانات.

نظام multi-region بيستخدم last-write-wins لرصيد المحفظة. مستخدم عمل إيداع من منطقة وسحب من منطقة تانية في نفس الثانية. إيه اللي ممكن يحصل؟

08

Redis Advanced: Atomicity و Streams و Rate Limiting

Lua scripts, sorted sets, streams and persistence trade-offs
Practical

Redis single-threaded command execution يجعل command atomic، لكن sequence من عدة commands ليست atomic دون MULTI/EXEC أو Lua script. Lua تنفذ check-and-update atomically على Redis server. حافظ على scripts قصيرة لأن script blocking يؤثر في latency.

Sorted Set جيد لل sliding window rate limit: score timestamp، member unique request ID؛ remove old entries، count current، add current، expire key. Redis Streams تقدم append-only entries، consumer groups، pending entries list و ack؛ تحتاج claim/reclaim abandoned messages ومراقبة lag.

Persistence: RDB snapshots و AOF trade-offs بين recovery point/startup time/disk. Replication لا تعني backup؛ accidental deletion/corruption قد يتكرر إلى replicas. احتفظ backups خارج failure domain واختبر restore. Redis cache policy eviction تختلف عن durable queue semantics.

LuaAtomic sliding-window limiter — simplified
-- KEYS[1] = rate-limit key
-- ARGV[1] = now_ms, ARGV[2] = window_ms, ARGV[3] = limit
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local cutoff = now - window
redis.call('ZREMRANGEBYSCORE', key, '-inf', cutoff)
local count = redis.call('ZCARD', key)
if count >= limit then return 0 end
redis.call('ZADD', key, now, tostring(now) .. ':' .. redis.call('INCR', key .. ':seq'))
redis.call('PEXPIRE', key, window)
return 1

الكود مبسط ويحتاج معالجة key expiry للـ sequence، unique member strategy، return remaining/retry-after، و cluster key-slot considerations. استخدم Redis Cluster hash tags عند الحاجة إلى مفاتيح متعددة في نفس Lua slot.

09

Object Storage و Data Placement

Blob versus relational data and lifecycle
Basics

Relational DB مناسبة لل transactional structured data و constraints/queries. Object storage مناسب للصور والفيديو والملفات الكبيرة والـ backups؛ يخزن blobs مع metadata/key. لا تخزن binary files الكبيرة في SQL لمجرد أن DB متاحة، إلا لو transaction/retention requirements تبرر ذلك.

Object key لا يكون public filename؛ استخدم opaque IDs، access policies، encryption، versioning، lifecycle/retention، checksum، malware scan، و signed URLs. Metadata table في SQL تربط owner/tenant/status/object key. Object storage consistency and versioning guarantees تختلف حسب provider؛ اقرأ docs.

10

Raft و Paxos: مستوى الفهم المطلوب

Consensus elects a leader and replicates a log
Deep dive

Consensus يتيح لمجموعة nodes الاتفاق على قيمة/ترتيب log رغم failures ضمن assumptions محددة. Raft يقسم المشكلة إلى leader election، log replication، safety. Leader term يزيد، candidate يحصل على votes، والـ leader ينسخ log entries إلى majority. Commit index يتقدم عندما replicated entries وفق rules.

Paxos و Raft خوارزميات معقدة وتفاصيلها تعتمد على timing/failure assumptions. كمطور تطبيقات، المطلوب غالبًا فهم لماذا majority/quorum مهم، لماذا split brain خطير، لماذا writes قد تتوقف عند فقد quorum، ولماذا consensus systems لا تحب latency العالية بين regions. لا تحتاج كتابة Raft بنفسك لبناء ASP.NET API.

ZooKeeper/etcd/Consul وبعض distributed databases تستخدم consensus concepts. لا تخلط replication العادية مع consensus؛ replication تنسخ data، consensus ينسق agreement/order under failures.

2PC و Sagas و Atomic Commit

Two-Phase Commit يطلب prepare ثم commit من participants عبر coordinator. يمكنه تحقيق atomic commit ضمن assumptions لكنه يضيف coordinator dependency، locks/resources held، blocking under coordinator/network failure، latency. كثير من cloud services لا توفر transaction موزعة عامة عبر DB/broker/HTTP provider.

Saga لا تحقق atomic rollback؛ هي سلسلة local commits وتعويضات business. استخدم 2PC فقط لو technology/participants يدعمونه والـ latency/blocking acceptable. استخدم Saga للـ long-running workflows، مع state persistence/manual repair. Outbox يحل dual-write داخل service boundary لكنه ليس distributed transaction.

Consensus: Raft بإيدك — انتخاب leader، replication، و partition

كل اللي فات في الدرس (quorum، vector clocks) بيتعامل مع التعارض بعد ما يحصل. الـ consensus بيمنعه من الأساس: مجموعة nodes بتتفق على ترتيب واحد للعمليات حتى لو بعضها وقع أو الشبكة اتقطعت. ده اللي شغّال جوه etcd (وبالتالي Kubernetes)، وجوه Kafka في وضع KRaft، وجوه قواعد بيانات زي CockroachDB. Raft هو الخوارزمية الأشهر لأنه اتصمم عشان يتفهم.

الفكرة في تلات قواعد:

  • Term + أغلبية: الوقت متقسم لـ terms. الـ follower اللي ما سمعش من leader لمدة عشوائية بيزوّد الـ term ويطلب أصوات. كل node ليها صوت واحد في الـ term، واللي ياخد أغلبية يبقى leader. أغلبيتين في نفس الـ term مستحيل، لأن أي أغلبيتين لازم يشتركوا في node.
  • Log replication: الكتابة بتروح للـ leader بس، بيضيفها في الـ log ويبعتها. الـ entry بتبقى committed لما تتخزن على أغلبية، وساعتها بس ينفع تتنفذ ويترد على العميل.
  • Election restriction: الـ node ما بتدّيش صوتها لمرشح الـ log بتاعه أقدم من بتاعها. ده اللي بيضمن إن أي leader جديد عنده كل اللي اتعمل له commit.
حدود المحاكاةدي محاكاة تعليمية في process واحد: الرسائل بتوصل فورًا جوه نفس الـ partition، ومفيش persistence على disk ولا snapshots ولا تغيير عضوية. بتورّي منطق الأمان بتاع Raft، ومش بديل عن مكتبة production. في الشغل الحقيقي بتستخدم etcd أو مكتبة مجرَّبة، ومابتكتبش consensus بنفسك.
Pythonraft.py — 5 nodes: election, replication, a partition with two leaders, healing, and 300 random schedulesExecuted ✓
import random

class Node:
    def __init__(self, i, n, rng):
        self.id, self.n, self.rng = i, n, rng
        self.term, self.voted_for, self.log = 0, None, []   # log: list of (term, command)
        self.commit, self.role, self.leader_ticks = 0, "follower", 0
        self.reset_timer()
        self.next_index = {}

    def reset_timer(self):
        self.timer = self.rng.randint(10, 20)          # randomized election timeout

    def last(self):
        return (self.log[-1][0] if self.log else 0, len(self.log))

class Cluster:
    def __init__(self, n=5, seed=7, restrict=True):
        self.restrict = restrict
        self.rng = random.Random(seed)
        self.nodes = [Node(i, n, self.rng) for i in range(n)]
        self.groups = [set(range(n))]                  # network partitions
        self.elections = 0

    def reach(self, a, b):
        return any(a in g and b in g for g in self.groups)

    def step_down(self, node, term):
        if term > node.term:
            node.term, node.voted_for, node.role = term, None, "follower"

    def request_vote(self, cand, peer):
        self.step_down(peer, cand.term)
        up_to_date = cand.last() >= peer.last() or not self.restrict   # election restriction
        if cand.term == peer.term and peer.voted_for in (None, cand.id) and up_to_date:
            peer.voted_for = cand.id
            peer.reset_timer()
            return True
        self.step_down(cand, peer.term)
        return False

    def append_entries(self, leader, peer):
        if leader.term < peer.term:
            self.step_down(leader, peer.term)
            return
        self.step_down(peer, leader.term)
        peer.role = "follower"
        peer.reset_timer()
        ni = leader.next_index[peer.id]
        prev_term = leader.log[ni - 1][0] if ni > 0 else 0
        if ni > len(peer.log) or (ni > 0 and peer.log[ni - 1][0] != prev_term):
            leader.next_index[peer.id] = max(0, ni - 1)   # consistency check failed: back up
            return
        peer.log = peer.log[:ni] + leader.log[ni:]        # overwrite any conflicting suffix
        leader.next_index[peer.id] = len(leader.log)
        peer.commit = min(leader.commit, len(peer.log))

    def tick(self):
        for node in self.nodes:
            if node.role == "leader":
                for p in self.nodes:
                    if p is not node and self.reach(node.id, p.id) and node.role == "leader":
                        self.append_entries(node, p)
                if node.role != "leader":
                    continue
                # commit rule: majority match AND the entry is from the current term
                for idx in range(len(node.log), node.commit, -1):
                    match = 1 + sum(1 for p in self.nodes if p is not node
                                    and self.reach(node.id, p.id)
                                    and node.next_index[p.id] >= idx
                                    and p.log[:idx] == node.log[:idx])
                    if match > node.n // 2 and node.log[idx - 1][0] == node.term:
                        node.commit = idx
                        break
                continue
            node.timer -= 1
            if node.timer <= 0:                           # timeout: start an election
                self.elections += 1
                node.term += 1
                node.role, node.voted_for = "candidate", node.id
                node.reset_timer()
                votes = 1 + sum(self.request_vote(node, p) for p in self.nodes
                                if p is not node and self.reach(node.id, p.id))
                if node.role == "candidate" and votes > node.n // 2:
                    node.role = "leader"
                    node.next_index = {p.id: len(node.log) for p in self.nodes}

    def run(self, ticks):
        for _ in range(ticks):
            self.tick()

    def leaders(self):
        return [n for n in self.nodes if n.role == "leader"]

    def show(self, title):
        print(f"\n== {title}")
        for n in self.nodes:
            cmds = " ".join(f"{c}@t{t}" for t, c in n.log) or "-"
            print(f"  n{n.id} {n.role:<9} term={n.term} commit={n.commit}  log: {cmds}")

c = Cluster()
c.run(40)
c.show("1) startup: one leader elected")
L = c.leaders()[0]
for cmd in ("x=1", "x=2"):
    L.log.append((L.term, cmd))
c.run(5)
c.show("2) two writes replicated and committed")

minority = {L.id, (L.id + 1) % 5}
c.groups = [minority, set(range(5)) - minority]
L.log.append((L.term, "x=99"))                           # client writes to the cut-off leader
c.run(60)
new = [n for n in c.leaders() if n.id not in minority][0]
new.log.append((new.term, "x=3"))
c.run(5)
c.show(f"3) partition: old leader n{L.id} isolated with n{(L.id+1)%5}")
print(f"  leaders right now: {[f'n{n.id}(term {n.term})' for n in c.leaders()]}")
print(f"  x=99 committed on old leader? {L.commit >= 3}   x=3 committed on new leader? {new.commit >= 3}")

c.groups = [set(range(5))]
c.run(30)
c.show("4) partition healed")
logs = {tuple(n.log) for n in c.nodes}
print(f"  identical logs on all nodes: {len(logs) == 1}   leaders: {len(c.leaders())}")
print(f"  x=99 survived anywhere: {any(cmd == 'x=99' for n in c.nodes for _, cmd in n.log)}")

def stress(restrict):
    two = lost = 0
    for seed in range(300):
        c = Cluster(seed=seed, restrict=restrict)
        rng = random.Random(seed)
        committed = set()                                # (index, entry) ever seen committed
        for t in range(400):
            if t % 50 == 25:
                ids = list(range(5)); rng.shuffle(ids)
                k = rng.choice([1, 2])
                c.groups = [set(ids[:k]), set(ids[k:])]
            if t % 50 == 0:
                c.groups = [set(range(5))]
            for ld in c.leaders():
                if rng.random() < 0.3:
                    ld.log.append((ld.term, f"w{t}"))
            c.tick()
            terms = [ld.term for ld in c.leaders()]
            two += len(terms) != len(set(terms))
            for n in c.nodes:
                committed.update((i, n.log[i]) for i in range(min(n.commit, len(n.log))))
        c.groups = [set(range(5))]
        c.run(60)
        final = c.nodes[0].log
        lost += any(i >= len(final) or final[i] != e for i, e in committed)
    return two, lost

print("\n== 5) 300 random schedules with repeated partitions")
for restrict in (True, False):
    two, lost = stress(restrict)
    name = "full Raft" if restrict else "without the election restriction"
    print(f"  {name:<34} two leaders in one term: {two}   runs that lost a committed entry: {lost} / 300")
ConsoleOutput — captured from a real run
== 1) startup: one leader elected
  n0 follower  term=1 commit=0  log: -
  n1 follower  term=1 commit=0  log: -
  n2 follower  term=1 commit=0  log: -
  n3 follower  term=1 commit=0  log: -
  n4 leader    term=1 commit=0  log: -

== 2) two writes replicated and committed
  n0 follower  term=1 commit=2  log: x=1@t1 x=2@t1
  n1 follower  term=1 commit=2  log: x=1@t1 x=2@t1
  n2 follower  term=1 commit=2  log: x=1@t1 x=2@t1
  n3 follower  term=1 commit=2  log: x=1@t1 x=2@t1
  n4 leader    term=1 commit=2  log: x=1@t1 x=2@t1

== 3) partition: old leader n4 isolated with n0
  n0 follower  term=1 commit=2  log: x=1@t1 x=2@t1 x=99@t1
  n1 follower  term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n2 follower  term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n3 leader    term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n4 leader    term=1 commit=2  log: x=1@t1 x=2@t1 x=99@t1
  leaders right now: ['n3(term 2)', 'n4(term 1)']
  x=99 committed on old leader? False   x=3 committed on new leader? True

== 4) partition healed
  n0 follower  term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n1 follower  term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n2 follower  term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n3 leader    term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  n4 follower  term=2 commit=3  log: x=1@t1 x=2@t1 x=3@t2
  identical logs on all nodes: True   leaders: 1
  x=99 survived anywhere: False

== 5) 300 random schedules with repeated partitions
  full Raft                          two leaders in one term: 0   runs that lost a committed entry: 0 / 300
  without the election restriction   two leaders in one term: 0   runs that lost a committed entry: 300 / 300

1 و2) الوضع الطبيعي: الـ timeouts العشوائية خلّت node واحدة تسبق وتكسب term 1، والكتابتين اتنسخوا على الخمسة و commit=2 عند الكل.

3) الـ partition: الـ leader القديم اتعزل مع node واحدة. لاحظ إن في اللحظة دي فيه اتنين leaders فعلًا، وده مش bug: كل واحد في term مختلف. اللي بيحمي البيانات إن القديم معاه 2 من 5 بس، فالكتابة x=99 فضلت في الـ log بتاعه من غير commit، يعني العميل ما اتردّش عليه بنجاح. الناحية التانية (3 من 5) انتخبت leader في term 2 وعملت commit لـ x=3.

4) بعد ما الشبكة رجعت: الـ leader القديم شاف term أعلى فنزل follower، والـ x=99 اتمسحت واتكتب مكانها x=3. ده صح: كتابة ما اتعملهاش commit مسموح تضيع، وكتابة اتعملها commit ممنوع. عشان كده العميل لازم يعتبر الـ timeout «مش عارف» مش «فشلت»، ويعيد المحاولة بـ idempotency key.

5) اختبار الأمان: على 300 جدول عشوائي فيه partitions متكررة، Raft الكامل ما ضيّعش ولا entry اتعملها commit، وما ظهرش leaderين في نفس الـ term. لما شلنا شرط الـ election restriction بس، كل الـ 300 تشغيلة ضيّعت بيانات committed: node متأخرة بتكسب الانتخاب وتمسح اللي الأغلبية أكدته. سطر واحد في الشرط هو الفرق بين نظام آمن ونظام بيضيّع بيانات في صمت.

التمن: كل كتابة محتاجة round trip لأغلبية، فالـ latency بتاعتها هي latency تاني أبطأ node في الأغلبية. والمجموعة اللي فقدت الأغلبية بتقف عن الكتابة خالص: ده اختيار consistency على availability (CP في CAP). 5 nodes بتتحمل وقوع 2، و3 بتتحمل 1، والعدد الزوجي ما بيزوّدش تحمّل.

cluster من 5 nodes بـ Raft اتقسم 2 و3. عميل بعت كتابة للـ leader القديم اللي في مجموعة الـ 2. إيه اللي بيحصل؟

ليه الـ election timeout في Raft عشوائي؟

ليه مابنستخدمش Raft لكل البيانات في النظام؟
لأن كل كتابة بتعدّي على leader واحد وبتستنى أغلبية، فالـ throughput محدود بـ node واحدة والـ latency بتزيد مع بُعد الـ nodes. الاستخدام الشائع: Raft للـ metadata الصغيرة الحرجة (مين الـ leader، الـ config، الـ locks)، أو Raft group لكل shard زي ما CockroachDB بيعمل، والبيانات الكبيرة بتتنسخ بطرق أرخص.
11

Failure Testing و Recovery Objectives

RPO, RTO, backup, restore and disaster recovery
Practical

RPO = أقصى data loss window مقبول. RTO = أقصى downtime مقبول. Backup schedule يجب أن يحقق RPO، و restore process يجب أن يحقق RTO. Replica في نفس region لا تحمي من region loss أو accidental deletion. Immutable/offsite backups تقلل ransomware/corruption risk.

اختبر restore إلى بيئة معزولة، تحقق من consistency/schema/migrations، ثم application startup و smoke tests. Disaster recovery runbook يحدد decision authority، failover order، DNS/traffic switch، secrets/config، data validation، communication، و failback. لا تعتبر backup job green دليلًا على قابلية الاستعادة.

Chaos/failure drills: kill node، isolate network، delay replication، lose quorum، expire lease، restore backup، rotate credentials. حدد blast radius و abort conditions، ولا تجرب destructive failures في production بلا safety plan.

12

Checklist نهائي لتصميم Distributed System

Consistency, ownership, failure and operations
Practical

قبل اعتماد design، أجب: من يملك كل data؟ ما consistency المطلوبة لكل read/write؟ ما happens عند network partition؟ هل operations idempotent؟ كيف يتم ordering؟ ما الذي يعاد تشغيله؟ كيف يتم failover/fencing؟ ما RPO/RTO؟ كيف نرصد lag/hot partitions؟ كيف نعيد بناء projections/cache؟ كيف نعمل schema migration؟

لا تحاول تحقيق global strong consistency لكل شيء. اختر boundaries: payment ledger strong, product search eventual, analytics delayed, user preferences read-your-writes. اجعل هذه trade-offs موثقة ومفهومة للـ product team.

13

اختبر Distributed Systems Fundamentals

Knowledge check
Practical
هل timeout يثبت أن server لم ينفذ العملية؟
لا؛ قد يكون نفذها والرد ضاع، لذلك النتيجة ambiguous.
ما trade-off أثناء partition في CAP؟
لا يمكن ضمان linearizable consistency و availability لكل request معًا؛ تختار سلوكًا حسب نوع العملية.
هل read replica تضمن read-after-write؟
لا؛ async replication قد تتأخر. استخدم primary/session consistency أو آلية انتظار مناسبة.
هل consistent hashing يحل hot key؟
لا؛ يوزع keys بين nodes لكنه لا يقسم key واحدة شديدة النشاط تلقائيًا.
ليه fencing token أفضل من الاعتماد على lease TTL فقط؟
لأنه يمنع stale owner من تنفيذ writes بعد انتهاء lease إذا كان storage يتحقق من monotonic token.
↗

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

References & further reading

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

التوثيق الرسمي — Official documentation

خريطة التغطية: 13 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionConsistency Models§01
New sectionReplication§01
New sectionPartitioning (Sharding)§03
New sectionCAP and PACELC§03
SuggestedConsistency Models§03
SuggestedReplication§05
SuggestedPartitioning (Sharding)§05
SuggestedCAP and PACELC§06
SuggestedDistributed Locks§06
SuggestedAdvanced Redis: Lua, Streams, Rate Limiting§06
SuggestedObject / Blob Storage§07
SuggestedOrdering and Clocks§01
SuggestedRaft / Paxos internals§01

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

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