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

أساسيات تصميم الأنظمة من المتطلبات إلى السعة

System Design Foundations

Requirements, capacity estimation, latency, scaling, load balancing, caching, database scaling and failure-aware design.

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

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

  • تحوّل افتراضات product لـ QPS وتخزين وbandwidth وعدد instances.
  • تستخدم تحليل الحساسية عشان تعرف أنهي افتراض بيقلب التصميم.

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

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

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

FOUNDATIONS FIRSTلاحقًا | Distributed systems internals and complex large-scale architecture.

01

يعني إيه System Design؟

From requirements to an operable architecture
Deep dive

System Design هو عملية تحويل احتياج business إلى نظام software يمكن تشغيله وتطويره وتحمله تحت حمل حقيقي. مش المقصود إنك ترسم مربعات كثيرة أو تختار Microservices من البداية. أنت بتحدد ما الذي يجب أن يفعله النظام، ما الحدود التي يجب ألا يتجاوزها، ثم تختار أبسط architecture تحقق المطلوب مع مساحة نمو معقولة.

التصميم الجيد يربط بين أربعة أشياء: requirements، workload، failure model، و operational capability. نفس feature ممكن تتصمم بشكل مختلف لو عندك 500 مستخدم داخلي مقابل 5 مليون مستخدم عالمي، أو لو فقدان رسالة مقبول مقابل تحويل مالي لا يجوز تكراره.

فكر في التصميم كسلسلة قرارات قابلة للتفسير: لماذا SQL وليس NoSQL؟ لماذا queue؟ هل نحتاج cache؟ ماذا يحدث لو Redis وقع؟ ما تكلفة consistency؟ وما طريقة اكتشاف المشكلة؟ القرار المحترف لا يقول «Kafka أفضل»؛ بل يشرح workload والقيود والبدائل والتكلفة.

قاعدة أساسيةابدأ بـ Modular Monolith + Relational Database + Cache/Queue عند الحاجة. لا تبدأ بتوزيع النظام إلا عندما يوجد سبب واضح: independent scaling، ownership، release autonomy، أو isolation.
02

Requirements: افصل الوظيفة عن الجودة

Functional and non-functional requirements
Deep dive

Functional Requirements تصف ما يفعله النظام: المستخدم ينشئ طلبًا، يضيف منتجًا للسلة، يتابع الشحنة، أو يسترجع ملفًا. اكتبها كسيناريوهات قابلة للاختبار، لا كأسماء صفحات.

Non-Functional Requirements (NFRs) تصف خصائص التشغيل: latency، throughput، availability، durability، security، privacy، consistency، scalability، maintainability، cost. كلمة «سريع» ليست requirement؛ قل مثلًا: 95% من قراءات صفحة المنتج أقل من 250ms عند 2,000 requests/sec في المنطقة الأساسية.

حدد workload profile: عدد المستخدمين النشطين، peak-to-average ratio، read/write ratio، payload size، geographic distribution، burst duration، retention، growth. كذلك حدد critical journeys والـ SLO لكل واحدة. لا تساوي بين endpoint بحث غير حرج و endpoint تأكيد دفع.

TextExample requirements — order platform
Functional:
- Customer can create an order from available items.
- Payment provider is called once per logical payment attempt.
- Inventory cannot be oversold beyond configured policy.
- Customer can query order status.

Non-functional:
- 99.9% monthly availability for checkout API.
- p95 read latency < 200 ms at 1,500 RPS.
- Payment commands are durable after acceptance.
- PII encrypted in transit and at rest.
- Recovery point objective (RPO) <= 5 minutes.

حوّل كل NFR إلى طريقة قياس واختبار. Availability لها denominator و window. Latency لازم تقول percentile وليس average فقط. Durability تحتاج failure scenarios. Security تحتاج threat model. Cost تحتاج budget أو unit economics.

03

Back-of-the-Envelope Estimation

QPS, storage, bandwidth and headroom
Practical

التقدير التقريبي لا يطلع رقمًا سحريًا؛ هو يكشف orders of magnitude ويمنع تصميمًا غير منطقي. اكتب assumptions بوضوح، ثم احسب average و peak مع headroom. افصل reads عن writes، لأنهم قد يذهبوا إلى مسارات مختلفة.

مثال: 2 مليون مستخدم نشط شهريًا، 10% يوميًا، كل مستخدم 20 request/day. إذن daily requests = 2,000,000 × 0.1 × 20 = 4,000,000. المتوسط = 4,000,000 / 86,400 ≈ 46 RPS. لو peak factor = 8، peak تقريبي ≈ 370 RPS. أضف burst behavior بدل افتراض توزيع ثابت.

Storage: 100 ألف order/day × 2 KB/order × 365 ≈ 73 GB/year raw. الفهارس والنسخ والـ logs والـ backups ترفع الرقم. Bandwidth: 400 RPS × 30 KB response ≈ 12 MB/s ≈ 96 Mbps قبل protocol overhead/CDN. الأرقام تتغير بشدة لو payloads كبيرة أو صور.

C#Tiny capacity calculator
static double AverageRps(long requestsPerDay) => requestsPerDay / 86_400d;
static double PeakRps(double averageRps, double peakFactor) => averageRps * peakFactor;
static double StorageGb(long records, double bytesPerRecord, int days) =>
    records * bytesPerRecord * days / 1_000_000_000d;

var avg = AverageRps(4_000_000);
Console.WriteLine($"Average: {avg:F1} RPS");
Console.WriteLine($"Peak: {PeakRps(avg, 8):F0} RPS");

لا تنسِ replication factor، compression، retention، indexes، write amplification، retry traffic، cache misses، و background jobs. اعمل capacity plan عند peak وليس المتوسط، واختبر graceful degradation لما تتجاوز السعة.

Capacity Estimation كحساب مش كتخمين

التقدير مش هدفه رقم دقيق — هدفه يقولك نوع النظام اللي بتبنيه: هل قاعدة بيانات واحدة تكفي؟ هل الـ cache اختياري ولا إجباري؟ فين الـ bottleneck؟ الكود ده بيحوّل افتراضات product لأرقام هندسية، وبيورّيك أنهي افتراض لو اتغيّر بيقلب التصميم.

Pythoncapacity.py — a photo-sharing service: every number is derived from a stated assumptionExecuted ✓
import math

A = {   # ---- assumptions: write them down, they are the real design input ----
    "daily_active_users":      2_000_000,
    "views_per_user_per_day":  40,          # feed items opened
    "uploads_per_user_per_day": 0.2,        # 1 photo every 5 days on average
    "photo_bytes":             1_500_000,   # original
    "thumbnail_bytes":         60_000,
    "metadata_bytes":          600,         # row in the database
    "peak_to_average":         4,           # evening peak
    "retention_years":         5,
    "replication_factor":      3,
    "requests_per_instance":   400,         # measured capacity of ONE app instance at target latency
    "target_utilisation":      0.6,         # headroom for failures and spikes
    "cache_hit_ratio":         0.9,
}
DAY = 86_400

def human(n, unit=""):
    for scale, name in [(1e15, "P"), (1e12, "T"), (1e9, "G"), (1e6, "M"), (1e3, "k")]:
        if n >= scale:
            return f"{n / scale:,.1f} {name}{unit}"
    return f"{n:,.0f} {unit}"

def estimate(a):
    reads_day, writes_day = a["daily_active_users"] * a["views_per_user_per_day"], a["daily_active_users"] * a["uploads_per_user_per_day"]
    read_qps, write_qps = reads_day / DAY, writes_day / DAY
    peak_read = read_qps * a["peak_to_average"]
    blob_year = writes_day * 365 * (a["photo_bytes"] + a["thumbnail_bytes"]) * a["replication_factor"]
    meta_total = writes_day * 365 * a["retention_years"] * a["metadata_bytes"]
    egress = peak_read * a["thumbnail_bytes"] * 8                              # bits per second at peak
    origin_qps = peak_read * (1 - a["cache_hit_ratio"])                        # what reaches the app after the CDN/cache
    instances = math.ceil(origin_qps / (a["requests_per_instance"] * a["target_utilisation"])) + 1   # +1: survive losing one
    return dict(read_qps=read_qps, write_qps=write_qps, ratio=read_qps / write_qps, peak_read=peak_read, blob_year=blob_year,
                blob_total=blob_year * a["retention_years"], meta_total=meta_total, egress=egress, origin_qps=origin_qps, instances=instances)

e = estimate(A)
print(f"average reads   : {e['read_qps']:>10,.0f} /s      writes: {e['write_qps']:,.1f} /s      read:write = {e['ratio']:,.0f}:1")
print(f"peak reads      : {e['peak_read']:>10,.0f} /s")
print(f"object storage  : {human(e['blob_year'], 'B')} per year, {human(e['blob_total'], 'B')} over {A['retention_years']} years (x{A['replication_factor']} replicas)")
print(f"metadata        : {human(e['meta_total'], 'B')} over {A['retention_years']} years")
print(f"peak egress     : {human(e['egress'], 'bit/s')}")
print(f"origin at peak  : {e['origin_qps']:>10,.0f} /s  -> {e['instances']} app instances")

print("\nsensitivity — change ONE assumption, watch the design move:")
for label, change in [("cache hit ratio 0.90 -> 0.50", {"cache_hit_ratio": 0.5}),
                      ("no cache at all", {"cache_hit_ratio": 0.0}),
                      ("peak factor 4 -> 10 (viral event)", {"peak_to_average": 10}),
                      ("uploads x5 (video-like usage)", {"uploads_per_user_per_day": 1.0})]:
    x = estimate({**A, **change})
    print(f"  {label:<36} instances={x['instances']:>4}   storage/5y={human(x['blob_total'], 'B'):>9}   peak egress={human(x['egress'], 'bit/s')}")
ConsoleOutput — captured from a real run
average reads   :        926 /s      writes: 4.6 /s      read:write = 200:1
peak reads      :      3,704 /s
object storage  : 683.3 TB per year, 3.4 PB over 5 years (x3 replicas)
metadata        : 438.0 GB over 5 years
peak egress     : 1.8 Gbit/s
origin at peak  :        370 /s  -> 3 app instances

sensitivity — change ONE assumption, watch the design move:
  cache hit ratio 0.90 -> 0.50         instances=   9   storage/5y=   3.4 PB   peak egress=1.8 Gbit/s
  no cache at all                      instances=  17   storage/5y=   3.4 PB   peak egress=1.8 Gbit/s
  peak factor 4 -> 10 (viral event)    instances=   5   storage/5y=   3.4 PB   peak egress=4.4 Gbit/s
  uploads x5 (video-like usage)        instances=   3   storage/5y=  17.1 PB   peak egress=1.8 Gbit/s

اقرأ النتيجة كقرارات: القراءة 200 ضعف الكتابة ⇒ النظام read-heavy: الـ cache والـ CDN جزء من التصميم مش تحسين لاحق. الكتابة أقل من 5 في الثانية والـ metadata مئات الجيجابايتات على 5 سنين ⇒ قاعدة بيانات relational واحدة (مع replicas) تكفي؛ مفيش أي داعي لـ sharding. الـ blobs بالبيتابايتات ⇒ object storage مع lifecycle policy، وده أكبر بند تكلفة في النظام كله.

تحليل الحساسية هو الجزء المهم: من غير cache عدد الـ instances بيطلع من 3 لـ 17 — يعني وقوع الـ cache حدث capacity مش مجرد «بطء»، ولازم له خطة. الـ viral event بيضرب الـ egress أكتر من الـ compute. ولو الـ uploads زادت 5 مرات، الـ compute ما اتحركش أصلًا والتخزين هو اللي اتضرب في 5.

مصدر كل رقم: requests_per_instance لازم يبقى مقاس بـ load test على خدمتك، مش مفترض. والـ target_utilisation 60% مش إسراف: هو اللي بيخليك تتحمل وقوع instance أو zone من غير ما الباقي يغرق.

التقدير طلّع 50 write/s و90,000 read/s. أنهي استنتاج تصميمي هو الأقوى؟

04

Latency و Throughput و Tail Latency

Measure user experience, not only averages
Deep dive

Latency زمن إتمام request. Throughput عدد العمليات المكتملة في وحدة زمن. Concurrency عدد العمليات الموجودة في نفس الوقت. يمكن أن يزيد throughput بينما latency تتدهور لو النظام اقترب من saturation.

استخدم percentiles: p50 يصف المنتصف، p95 يعني 95% من الطلبات أسرع من هذه القيمة، و p99 يكشف tail. Average قد يخفي أن 1% من العملاء ينتظرون 8 ثوانٍ. Tail latency تتضخم عندما تجمع عدة dependencies؛ لو كل واحدة p99=100ms فاحتمال أن كل request يلمس عدة خدمات بطيئة يصبح أكبر.

قانون Little: L = λ × W؛ عدد الطلبات في النظام (L) يساوي arrival rate (λ) مضروبًا في زمن البقاء (W)، بافتراض steady state. عند 200 RPS وزمن متوسط 0.25s، تتوقع تقريبًا 50 request in flight. لو latency ارتفعت إلى 2s يصبح العدد 400، ما يزيد ضغط الذاكرة والاتصالات.

حسّن critical path: قلل network hops، تجنب N+1 queries، ضع limits على payloads، استخدم indexes، parallelize independent I/O بحذر، و cache stable reads. لا تجعل parallelism يضاعف الضغط على dependency الضعيفة. حدّد timeout budget end-to-end ووزعه على downstream calls.

05

Vertical vs Horizontal Scaling

Scale up, scale out and statelessness
Deep dive

Vertical scaling زيادة CPU/RAM/IOPS في نفس node. سهلة نسبيًا وتقلل تعقيد التوزيع، لكنها لها سقف و single-node failure domain. Horizontal scaling إضافة instances؛ تزيد capacity و availability المحتملة، لكنها تتطلب stateless compute، shared/distributed state، load balancing، coordination، deployment discipline.

اجعل web/API instances stateless قدر الإمكان: لا تحفظ session أو uploaded files على local disk باعتبارها مصدر الحقيقة. استخدم distributed cache/session store أو token claims بحذر، و object storage للملفات. Background workers تحتاج concurrency controls و idempotency عند تشغيل عدة replicas.

Scale لا يعني إضافة replicas فقط. عنق الزجاجة قد يكون database connection pool، lock contention، hot partition، third-party quota، أو queue consumer. استخدم load test و profiling لتحديد bottleneck. لو DB هي bottleneck، مضاعفة API replicas قد تزيد المشكلة.

ClientsWeb / MobileLoad BalancerHealth awareAPI AStatelessAPI BStatelessAPI CStatelessShared StateDB / Cache
A stateless API tier can scale horizontally behind a load balancer

Load balancer يوزع الطلبات على healthy instances. Session affinity (sticky sessions) قد تسهّل migration مؤقتًا لكنها تقلل مرونة التوزيع ولا تعالج shared state؛ لا تجعلها بديلًا عن تصميم stateless.

06

Load Balancing و Reverse Proxy و CDN

Traffic distribution at the edge
Deep dive

Reverse Proxy يستقبل traffic نيابة عن servers: TLS termination، routing، compression، request limits، headers، static content، وربما caching. Load Balancer يوزع traffic على عدة backends. كثير من المنتجات تجمع الوظيفتين. CDN يوزع cached content قرب المستخدمين عبر edge locations.

Algorithms: round robin بسيط، weighted round robin للأحجام المختلفة، least connections للطلبات متفاوتة المدة، consistent hashing للـ affinity/cache locality. Health checks تمنع إرسال traffic إلى instance غير جاهزة، لكن health endpoint يجب ألا يعلن readiness لمجرد أن process يعمل.

Layer 4 يوزع TCP/UDP connections دون فهم HTTP semantics غالبًا. Layer 7 يفهم HTTP host/path/headers ويمكنه routing حسب URL أو tenant. TLS termination يخفف عبء التطبيقات لكن يحتاج حماية traffic داخل الشبكة وإدارة certificates و trusted forwarded headers.

CDN ممتاز للصور و JS/CSS والملفات العامة وبعض GET responses. لا تخزن private user-specific responses في shared cache دون cache key وسياسات دقيقة. purge/invalidation و TTL و stale content جزء من التصميم، لا تفصيل بعد النشر.

07

Caching Strategies

Cache-aside, write-through, TTL and invalidation
Deep dive

Cache يخزن نسخة مشتقة أو قابلة لإعادة البناء لتقليل latency/load. أهم قرار ليس اختيار Redis؛ بل تعريف source of truth، freshness requirement، cache key، TTL، invalidation، behavior on miss/failure.

Cache-aside: التطبيق يقرأ cache، لو miss يقرأ DB ثم يكتب cache. سهل ومرن لكنه يسمح stale window و cache stampede. Write-through: الكتابة تمر عبر cache إلى store بشكل متزامن؛ consistency أبسط نسبيًا لكن latency/availability ترتبط بالمسارين. Write-behind: cache يؤجل الكتابة؛ throughput عالٍ لكن خطر فقدان البيانات وتعقيد recovery أعلى، فلا تستخدمه للبيانات الحرجة دون durability design.

C#Cache-aside with TTL and cancellation
public async Task<ProductDto?> GetProductAsync(Guid id, CancellationToken ct)
{
    var key = $"product:{id}:v1";
    var cached = await cache.GetStringAsync(key, ct);
    if (cached is not null) return JsonSerializer.Deserialize<ProductDto>(cached);

    var product = await db.Products.AsNoTracking()
        .Where(x => x.Id == id)
        .Select(x => new ProductDto(x.Id, x.Name, x.Price))
        .SingleOrDefaultAsync(ct);

    if (product is not null)
        await cache.SetStringAsync(key, JsonSerializer.Serialize(product),
            new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct);
    return product;
}

Cache invalidation choices: delete on write، update cached value، versioned keys، short TTL، event-driven invalidation. Deleting after DB commit يقلل stale window، لكن crash بين commit و delete قد يترك stale data. Transactional outbox event يقلل احتمال فقد invalidation event، لكنه لا يجعل cache transactionally consistent.

Cache stampede: آلاف requests على key منتهي الصلاحية تضرب DB معًا. استخدم single-flight/request coalescing، jittered TTL، stale-while-revalidate، distributed lock بحذر، أو pre-warming. Hot keys قد تحتاج replication أو local L1 cache، مع قبول consistency trade-off.

لا تخزن كل شيء في RedisCache ليس database دائمًا. لا تعتمد على cache وحده للـ orders/payments أو أي data لا يمكن إعادة بنائها، إلا إذا كان المنتج مصممًا كـ durable datastore مع persistence/replication/recovery.
08

Database Scaling: قبل Sharding

Indexes, read replicas, partitioning and connection pools
Deep dive

ابدأ بتحسين query/index/schema، ثم افحص connection pooling و locking و IOPS. استخدم EXPLAIN/Actual Execution Plan، راقب slow queries و deadlocks، وتجنب تحميل آلاف rows ثم filtering في memory. Pagination يجب أن تكون bounded؛ keyset pagination أفضل من deep OFFSET في كثير من feeds.

Read replicas تفصل جزءًا من reads عن primary، لكن replication lag يعني أن read-after-write قد يرجع قيمة قديمة. استخدم primary للقراءات الحساسة بعد write، أو session consistency/routing policy. لا تحول كل read تلقائيًا إلى replica من غير تعريف consistency requirement.

Partitioning يقسم جدولًا داخل database engine لتسهيل retention/maintenance/pruning؛ sharding يقسم البيانات على عدة database nodes. Partitioning لا يساوي horizontal sharding. Sharding يزيد تعقيد cross-shard queries، transactions، unique constraints، migrations، rebalancing، و hot shards.

Connection pool limit مهم: 20 API replicas × pool 100 قد تفتح 2,000 connections. زيادة replicas دون حساب database connection budget قد تستهلك DB. استخدم pooling، bounded concurrency، query timeouts، و load shedding.

09

Background Processing و Queue Fundamentals

Move slow and retryable work off the request path
Practical

استخدم background processing عندما لا يلزم إكمال العمل قبل response: إرسال email، توليد report، معالجة image، webhook delivery، أو workflow طويل. الـ API تقبل command وتكتب durable job/message ثم ترجع 202 Accepted أو status resource. لا تعتمد على fire-and-forget Task داخل web process؛ recycle/crash قد يفقد العمل.

Queue تفصل producer عن consumer وتوفر buffering. هذا يخفف traffic bursts لكنه لا يلغي capacity limits. إذا كان arrival rate أكبر من processing rate لفترة طويلة، queue depth ستزيد بلا حد. حدد max queue age، retention، dead-letter policy، backpressure، و consumer scaling.

C#HTTP endpoint accepts asynchronous work
app.MapPost("/reports", async (CreateReportRequest request,
    IReportJobPublisher publisher, CancellationToken ct) =>
{
    var jobId = Guid.NewGuid();
    await publisher.PublishAsync(new GenerateReport(jobId, request.CustomerId), ct);
    return Results.Accepted($"/reports/{jobId}", new { jobId, status = "queued" });
});

الـ publisher يجب أن يضمن durable acceptance قبل 202. لو حفظت job في DB ثم أرسلت broker message في خطوتين منفصلتين، قد يحدث dual-write failure؛ Outbox pattern يعالج هذا في الدرس الخاص بالـ Messaging.

10

Failures: Timeout و Retry و Idempotency

Assume partial failure at every network boundary
Deep dive

في distributed system، request قد يضيع، response قد يضيع بعد نجاح العملية، dependency قد تتأخر، DNS/TLS قد يفشل، connection قد ينقطع أثناء commit، و client قد يعيد المحاولة. لذلك timeout لا يعني أن العملية لم تحدث؛ يعني فقط أنك لم تعرف النتيجة في الوقت المحدد.

Retry مناسب للأخطاء transient فقط، مع bounded attempts، exponential backoff، jitter، global deadline، و retry budget. لا تعيد 400 validation error أو business rejection. لا تجعل كل layer تعيد 3 مرات؛ retries المتراكمة تضاعف traffic (3×3×3=27 محاولة محتملة). ضع retry في layer تملك context كافيًا.

Idempotency: تكرار نفس logical operation لا يكرر الأثر. مثال payment request يحمل idempotency key، يخزن server نتيجة المفتاح ويربطه بالطلب. استخدم unique constraint على (CustomerId, IdempotencyKey) مع hash للـ payload؛ إذا أعيد المفتاح مع payload مختلف ارفضه. لا تستخدم key عشوائيًا جديدًا عند كل retry.

SQLIdempotency key constraint
CREATE TABLE IdempotencyRecords (
    CustomerId uniqueidentifier NOT NULL,
    IdempotencyKey varchar(100) NOT NULL,
    RequestHash char(64) NOT NULL,
    ResponseJson nvarchar(max) NULL,
    Status varchar(20) NOT NULL,
    CreatedAt datetime2 NOT NULL,
    CONSTRAINT PK_IdempotencyRecords PRIMARY KEY (CustomerId, IdempotencyKey)
);

Rate limiting يحمي capacity والعدالة، لكنه ليس بديل authentication. Health checks تساعد orchestration، monitoring يكشف behavior، logs تعطي context، metrics تكشف trends. لا تسجل secrets أو payment data أو raw PII.

11

Trade-offs و Architecture Decision Records

Make decisions explicit and reversible when possible
Practical

كل اختيار له تكلفة. Strong consistency قد ترفع latency وتقلل availability أثناء partition. Cache يقلل read load لكنه يضيف invalidation. Microservices تعطي independent deployment لكنها تضيف network failures و observability و data ownership. Multi-region يحسن disaster tolerance لكنه يعقد writes/conflict resolution والتكلفة.

اكتب ADR قصيرة: Context، Decision، Alternatives، Consequences، Risks، Revisit trigger. مثال: «نستخدم SQL Server كـ source of truth للطلبات؛ Redis cache لقراءات catalog فقط؛ RabbitMQ للـ work async؛ لا نستخدم microservices الآن لأن team/domain لا يبرران تكلفة التشغيل».

TextADR template
# ADR-007: Queue order confirmation emails
Status: Accepted
Context: Email delivery is slow and retryable; HTTP response must stay fast.
Decision: Persist an outbox record in the order transaction and publish asynchronously.
Alternatives: Fire-and-forget task; direct SMTP call; scheduled DB polling.
Consequences: Eventual delivery, operational queue monitoring, idempotent consumer required.
Risks: Outbox backlog; poison messages; duplicate delivery attempts.
Revisit when: Throughput or latency SLO changes materially.

اختَر التصميم الأبسط الذي يحقق requirements الحالية ويترك upgrade path. لا تبني scale افتراضيًا لا تحتاجه، لكن لا تتجاهل failure modes التي ستكلف business أموالًا أو ثقة.

12

Availability و Reliability و SLI/SLO/SLA

Define what healthy means
Deep dive

Availability هي نسبة الوقت أو الطلبات التي تحقق تعريف الخدمة المتاحة. Reliability أوسع: هل الخدمة تؤدي المطلوب بشكل صحيح عبر الزمن؟ نظام يرد HTTP 200 لكنه يرجع بيانات خاطئة ليس reliable. Durability تعني أن البيانات المؤكدة لا تضيع ضمن ضمانات محددة. لا تخلط availability مع correctness أو durability.

لو SLO هو 99.9% خلال 30 يومًا، error budget تقريبًا 0.1% من الوقت/الطلبات وفق طريقة القياس. في 30 يومًا يوجد 43,200 دقيقة؛ 0.1% يساوي 43.2 دقيقة downtime-equivalent. لكن لو SLI request-based، احسب failed eligible requests / total eligible requests، لا تحولها إلى دقائق مباشرة.

اكتب SLI بوضوح: valid request، successful response، latency threshold، excluded traffic، measurement point. مثال checkout availability لا ينبغي أن تعتبر كل 4xx فشلًا؛ validation error بسبب client قد يكون response صحيحًا، بينما 5xx أو timeout failure. SLO يوجه engineering trade-offs، و SLA التزام خارجي يحتاج هامشًا أعلى من SLO الداخلي.

Use burn-rate alerts: تنبيه سريع لو error budget يُستهلك بسرعة كبيرة، وتنبيه أبطأ للانحراف المستمر. Alert على user impact لا على CPU 70% وحده. CPU قد يكون مرتفعًا مع latency ممتازة، أو منخفضًا بينما DB lock يوقف الطلبات.

13

Capacity Planning و Bottleneck Analysis

Find the limiting resource before scaling
Practical

السعة الفعلية للنظام هي أقل سعة في critical path. API قد تتحمل 5,000 RPS، لكن SQL pool أو payment provider يتحمل 300 فقط. ارسم dependency graph، وقس throughput/latency عند كل boundary. لا تجمع capacities حسابيًا إذا كان المسار sequential؛ throughput يحدده أبطأ component أو shared contention.

اختبر عند 50% و70% و90% من target peak، ثم burst أعلى لفترة قصيرة. راقب saturation: thread pool queue، DB connections، lock waits، broker lag، memory/GC، network bandwidth. قرب saturation، latency قد تقفز بشكل غير خطي؛ لذلك headroom مهم.

ضع capacity budget لكل dependency: max concurrency، timeout، retry budget، quota. لو API لديها 10 replicas وكل واحدة تفتح 80 DB connections، total potential 800؛ تأكد أن DB و pooler مصممان لذلك. Autoscaling يجب أن يراعي scale-up delay و cold starts، وليس مجرد CPU threshold.

TextCapacity budget example
Peak API:                 800 RPS
Catalog read dependency:  500 RPS
Payment provider:         80 RPS (business critical)
SQL connection budget:   240 concurrent sessions

Implications:
- Cache catalog reads; do not multiply SQL load with API replicas.
- Bound payment concurrency and queue non-urgent work.
- Autoscale API only within downstream budgets.
- Load shed low-priority traffic before payment saturation.
14

Data Lifecycle و Hot/Warm/Cold Data

Retention, archival and deletion are architecture concerns
Deep dive

ليس كل data تحتاج نفس latency أو retention. Hot data تُقرأ/تكتب كثيرًا وتحتاج indexes/cache. Warm data أقل استخدامًا ويمكن أن تنتقل إلى cheaper storage أو partition قديم. Cold data للأرشفة والامتثال والاسترجاع النادر. حدد lifecycle من البداية: retention، legal hold، deletion، backup retention، و restore access.

Partition by date قد يسهل حذف old partitions بدل DELETE ملايين rows. لكن partition key يؤثر في query pruning و index strategy. Archive data لا يعني نسيانها؛ يجب أن تعرف كيف تسترجعها وكم يستغرق ذلك وهل تدخل في customer export/deletion requests.

Soft delete مفيد لبعض workflows لكنه لا يحقق privacy erasure تلقائيًا. Backups وال replicas و search indexes و caches والـ object storage تحتاج deletion propagation policy. احتفظ audit metadata بالحد الأدنى المطلوب قانونيًا.

15

Security و Privacy جزء من التصميم

Threat modeling, tenant isolation and secrets
Deep dive

حدد assets، actors، trust boundaries، entry points، abuse cases. استخدم least privilege، encryption in transit/at rest، managed identities، secret rotation، audit trails، input validation، output encoding، secure defaults. لا تعتبر network داخلية موثوقة تلقائيًا.

Multi-tenant system يحتاج tenant isolation في database queries/cache keys/object paths/queue messages/log access. لا تعتمد على tenantId القادم من client دون ربطه بهوية مصرح لها. ضع tenant scope في data access layer واختبر cross-tenant access attempts. Cache key يجب أن يتضمن tenant/user scope إذا كانت النتيجة private.

PII minimization تقلل risk والتكلفة. لا تسجل access tokens أو passwords أو payment details. Define data classification، retention، encryption keys، audit access، و breach response. Security controls يجب أن تكون observable: failed auth rates، privilege changes، secret access anomalies.

16

Load Balancing و Tail Latency: ليه الـ p99 هو اللي بيحكم

Four balancing policies on the same workload, and how fan-out multiplies slow requests — executed
Deep dive

متوسط الـ latency رقم مريح ومضلل. المستخدم اللي بيشتكي هو اللي وقع في الـ 1% البطيئة — ولما صفحة واحدة بتنادي 20 خدمة، «الـ 1%» دي بتبقى حدث شبه مؤكد. الـ lab ده بيقيس حاجتين: أثر سياسة توزيع الحمل على الـ tail، وأثر الـ fan-out.

Pythonload_balancing.py — random, round robin, least connections, power-of-two-choices; then fan-outExecuted ✓
import heapq, random
random.seed(9)

def simulate(policy, servers=10, requests=60_000, arrival_rate=70.0):
    """Discrete-event simulation. Each server handles one request at a time; ~83 req/s total capacity (85% utilised).
    Service times are mostly fast with an occasional slow one (GC pause, cold cache)."""
    free_at = [0.0] * servers            # when each server finishes its current queue
    queue_len = [0] * servers
    completions = []                     # (finish_time, server) to keep queue lengths current
    t, rr, latencies = 0.0, 0, []
    for _ in range(requests):
        t += random.expovariate(arrival_rate)
        while completions and completions[0][0] <= t:
            queue_len[heapq.heappop(completions)[1]] -= 1
        if policy == "random":
            s = random.randrange(servers)
        elif policy == "round robin":
            s, rr = rr % servers, rr + 1
        elif policy == "least connections":
            s = min(range(servers), key=lambda i: queue_len[i])          # needs global, fresh state
        else:                                                            # power of two choices
            a, b = random.sample(range(servers), 2)
            s = a if queue_len[a] <= queue_len[b] else b                 # look at just TWO random servers
        service = random.expovariate(1 / 0.10) if random.random() > 0.02 else random.uniform(0.8, 1.5)
        start = max(t, free_at[s])
        free_at[s] = start + service
        queue_len[s] += 1
        heapq.heappush(completions, (free_at[s], s))
        latencies.append(free_at[s] - t)
    latencies.sort()
    pick = lambda q: latencies[int(len(latencies) * q)]
    return sum(latencies) / len(latencies), pick(0.50), pick(0.95), pick(0.99)

print(f"{'policy':<22}{'mean':>8}{'p50':>8}{'p95':>8}{'p99':>8}   (seconds, same arrival stream statistics)")
for policy in ("random", "round robin", "least connections", "power of two choices"):
    mean, p50, p95, p99 = simulate(policy)
    print(f"{policy:<22}{mean:>8.2f}{p50:>8.2f}{p95:>8.2f}{p99:>8.2f}")

# ---------- fan-out: one page needs N backend calls and waits for ALL of them ----------
print("\nfan-out: each backend call is slow (> 1 s) only 1% of the time")
print(f"{'calls per page':>15}{'P(page hits at least one slow call)':>38}{'simulated':>11}")
for n in (1, 5, 20, 100):
    exact = 1 - 0.99 ** n
    sim = sum(any(random.random() < 0.01 for _ in range(n)) for _ in range(20_000)) / 20_000
    print(f"{n:>15}{exact:>38.1%}{sim:>11.1%}")

# ---------- hedged requests: send a second copy if the first has not answered by the p95 ----------
def call():  return random.uniform(0.8, 1.5) if random.random() < 0.02 else random.expovariate(1 / 0.10)
plain = sorted(call() for _ in range(50_000))
hedge_after = plain[int(len(plain) * 0.95)]
hedged, extra = [], 0
for _ in range(50_000):
    first = call()
    if first <= hedge_after:
        hedged.append(first)
    else:
        extra += 1; hedged.append(min(first, hedge_after + call()))
hedged.sort()
print(f"\nhedging after {hedge_after * 1000:.0f} ms: p99 {plain[int(len(plain) * .99)]:.2f}s -> {hedged[int(len(hedged) * .99)]:.2f}s, "
      f"p99.9 {plain[int(len(plain) * .999)]:.2f}s -> {hedged[int(len(hedged) * .999)]:.2f}s, extra load {extra / 50_000:.1%}")
ConsoleOutput — captured from a real run
policy                    mean     p50     p95     p99   (seconds, same arrival stream statistics)
random                    1.05    0.64    3.46    5.42
round robin               0.86    0.47    2.93    4.08
least connections         0.20    0.12    0.71    1.39
power of two choices      0.35    0.22    1.24    1.76

fan-out: each backend call is slow (> 1 s) only 1% of the time
 calls per page   P(page hits at least one slow call)  simulated
              1                                  1.0%       1.0%
              5                                  4.9%       5.1%
             20                                 18.2%      18.7%
            100                                 63.4%      62.8%

hedging after 347 ms: p99 1.16s -> 0.46s, p99.9 1.47s -> 0.72s, extra load 4.9%

السياسات: نفس الـ servers ونفس الحمل، والفرق في الـ tail كبير. الـ random والـ round robin مش بيشوفوا حالة الـ servers، فبيبعتوا طلبات لـ server واقف على طلب بطيء. الـ least connections بيتجنب ده لكنه محتاج حالة لحظية عن كل الـ servers. والـ power of two choices — اختار اتنين عشوائي وابعت للأقل انشغالًا — بياخد أغلب الفايدة بمعلومة عن اتنين بس؛ عشان كده هو الأساس في load balancers كتير.

الـ fan-out: لما الصفحة محتاجة 100 نداء وكل نداء بطيء 1% من الوقت، أغلب الصفحات هتقابل نداء بطيء واحد على الأقل. الـ p99 بتاع الخدمة الواحدة بقى الـ median بتاع الصفحة. ده اللي بيخلي الـ tail latency مشكلة معمارية مش تفصيلة.

Hedged requests: لو الرد اتأخر عن الـ p95، ابعت نسخة تانية وخد أسرع رد. الـ tail بيتقصّ بتمن حمل إضافي صغير (حوالي 5%). شرطين: العملية idempotent، ومفيش hedging لما النظام أصلًا محمّل زيادة — وإلا بتزوّد الضغط.

خدمتك p99 بتاعها 800ms والمتوسط 60ms. صفحة الـ dashboard بتنادي 40 خدمة زيها بالتوازي. المستخدمين بيشتكوا من البطء «أغلب الوقت». ليه؟

17

مراجعة System Design Foundations

Knowledge check and practical checklist
Practical
ليه ما ينفعش نبدأ برسم Microservices قبل requirements؟
لأن حدود الخدمات والتوزيع قرارات ناتجة عن workload و ownership و SLOs؛ البدء بها يضيف تعقيدًا قبل معرفة الحاجة.
عند 4M requests/day، المتوسط التقريبي كام RPS؟
حوالي 46 RPS؛ ثم نضرب في peak factor لتقدير الذروة.
هل timeout معناه إن payment فشل؟
لا. قد يكون provider نفذ العملية لكن response ضاع؛ نحتاج idempotency/reconciliation.
ما الفرق بين partitioning و sharding؟
Partitioning تقسيم داخل database engine غالبًا، أما sharding فتوزيع data على nodes مستقلة.
إيه أخطر side effect من إضافة API replicas دون حساب؟
زيادة connections والضغط على database أو downstream dependencies.

قبل أي design: اكتب requirements، traffic estimates، data model، SLOs، failure scenarios، security boundaries، cost assumptions، observability plan، ثم قارن أبسط 2–3 alternatives.

↗

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

References & further reading

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

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

خريطة التغطية: 35 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapRequirements and Constraints§01
RoadmapFunctional vs Non-Functional Requirements§01
RoadmapScalability Fundamentals§01
RoadmapAvailability and Reliability§01
RoadmapLatency and Throughput§03
RoadmapLoad Balancing§04
RoadmapReverse Proxies§06
RoadmapCaching Strategies§07
RoadmapDatabase Scaling Concepts§08
RoadmapStateless Services§05
RoadmapBackground Processing§09
RoadmapMessage Queues Fundamentals§09
RoadmapFailures and Retries§10
RoadmapTimeouts§10
RoadmapIdempotency§09
RoadmapRate Limiting§09
RoadmapHealth Checks§09
RoadmapMonitoring and Logging§10
RoadmapTrade-Offs in Architecture§01
SuggestedBack-of-the-envelope estimation (QPS, storage, bandwidth)§17
SuggestedCAP and PACELC§17
SuggestedConsistency models: strong, eventual, causal§17
SuggestedReplication: leader-follower, multi-leader§17
SuggestedSharding and hot keys§17
SuggestedConsistent hashing§06
SuggestedCDN and edge caching§06
SuggestedAPI Gateway and BFF§07
SuggestedQueue vs event stream (RabbitMQ vs Kafka)§07
SuggestedBackpressure and load shedding§08
SuggestedCircuit breaker and bulkhead§08
SuggestedSLI, SLO, SLA, error budgets§08
SuggestedDistributed transactions and Saga§11
SuggestedMonolith vs Modular Monolith vs Microservices§11
SuggestedIdempotent consumers and the exactly-once myth§11
SuggestedBook: Designing Data-Intensive Applications§11

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

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