Failure Model و Timeout Budget
الـ failure modes الأساسية: connection refused، DNS/TLS failure، timeout، throttling، partial response، malformed response، dependency overload، process crash، network partition. صنّف errors: transient، permanent، business rejection، unknown outcome. كل نوع يحتاج سياسة مختلفة.
Timeout لازم يكون أقل من caller deadline، والـ downstream budgets تتوزع من end-to-end budget. مثال API budget 2s: auth 100ms، inventory 400ms، pricing 300ms، DB 500ms، margin 700ms. لا تستخدم timeout 30s لكل call ثم تتوقع API تنتهي خلال 2s.
CancellationToken يجب أن ينتقل عبر HttpClient/EF Core/queue handlers. cancellation من client لا يعني دائمًا rollback؛ لو العملية بدأت commit، تعامل مع ambiguous outcome عبر idempotency/status lookup.
builder.Services.AddHttpClient<IPricingClient, PricingClient>(client =>
{
client.BaseAddress = new Uri("https://pricing.internal/");
client.Timeout = TimeSpan.FromSeconds(2);
});
public async Task<Price?> GetAsync(Guid productId, CancellationToken ct)
{
using var response = await http.GetAsync($"prices/{productId}", ct);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<Price>(cancellationToken: ct);
}حساب Timeout و Retry End-to-End
افترض total deadline 2.5s، و attempt timeout 600ms، وثلاث محاولات مع delays 100ms و250ms. أسوأ زمن تقريبي = 3×600 + 100 + 250 = 2.15s، ويبقى 350ms للـ serialization/network overhead. لكن لو caller نفسه timeout عند 2s، المحاولات الأخيرة قد لا تكمل؛ propagate remaining deadline بدل بدء budget جديد عند كل service.
Retry amplification عبر 3 layers × 3 attempts لكل layer قد يصل إلى 27 downstream attempts. حدد retry owner واحدًا غالبًا، أو وزع budget محسوبًا. Circuit breaker يجب أن يرى failure signals المناسبة؛ لو retry يستهلك كل الأخطاء داخليًا، breaker قد لا يرى المشكلة إلا بعد timeout total.
Retry-After من provider يجب احترامه ضمن caller deadline. Jitter full/equal/decorrelated خيارات؛ المهم ألا تتزامن retries. سجل attempt number و delay و reason كـ telemetry attributes منخفضة cardinality.
Retry with Exponential Backoff و Jitter
Exponential backoff: delay grows مثل 200ms، 400ms، 800ms مع cap. Jitter يضيف randomness حتى لا تعيد كل instances المحاولة في اللحظة نفسها. حدد max attempts، max elapsed time، retryable status codes، و idempotency requirements.
Retry مفيد ل HTTP 429/503 أو connection reset حسب provider contract. احترم Retry-After. لا تعيد 401 دون refresh flow، ولا 400/validation، ولا business rejection. لو client request non-idempotent، retry قد ينشئ duplicate؛ استخدم idempotency key.
Retry amplification: كل client يعيد 3 مرات مع 1000 RPS يصبح حتى 3000 attempts. Retry storm قد يمنع recovery. استخدم retry budget ونسبة محدودة من total traffic، ووقف retries عند overload.
var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromMilliseconds(200),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<HttpRequestException>()
.HandleResult(r => r.StatusCode is HttpStatusCode.TooManyRequests
or HttpStatusCode.ServiceUnavailable)
})
.Build();راجع package/version API لأن Polly v8 resilience APIs تختلف عن القديم. لا تنسَ timeout strategy و circuit breaker و telemetry؛ المثال يوضح الفكرة وليس drop-in production config.
Retry Storm و Circuit Breaker: محاكاة عطل حقيقي
خدمة بتعتمد عليها بدأت تتعب (مش واقعة — بطيئة وبترفض جزء من الطلبات). رد الفعل البديهي «نعيد المحاولة» هو بالظبط اللي بيحوّل تعب مؤقت لانهيار: كل client بيضاعف الحمل في أسوأ لحظة. المحاكاة دي بتقيس ده.
import random
random.seed(2)
CAPACITY = 100 # requests the dependency can serve per tick when healthy
DEMAND = 60 # new user requests per tick
TICKS = 60
def capacity_at(t): # ticks 10-25: the dependency is degraded to 40% capacity
return 40 if 10 <= t < 26 else CAPACITY
def simulate(policy):
pending = [] # (due_tick, attempt)
ok = failed = sent_total = peak = shed = 0
breaker_open_until = consecutive_bad = 0
recovered_at = None
for t in range(TICKS):
arrivals = [(t, 1)] * DEMAND + [p for p in pending if p[0] == t]
pending = [p for p in pending if p[0] != t]
if policy == "breaker" and t < breaker_open_until:
shed += len(arrivals); failed += len(arrivals) # fail fast: nothing reaches the dependency
continue
sent_total += len(arrivals); peak = max(peak, len(arrivals))
random.shuffle(arrivals)
served, rejected = arrivals[:capacity_at(t)], arrivals[capacity_at(t):]
ok += len(served)
for _, attempt in rejected:
if policy == "no retry" or attempt >= 4:
failed += 1
elif policy == "immediate retry":
pending.append((t + 1, attempt + 1))
else: # backoff + jitter (also used with the breaker)
pending.append((t + 1 + int(random.uniform(0, 2 ** attempt)), attempt + 1))
if policy == "breaker":
consecutive_bad = consecutive_bad + 1 if len(rejected) > 0.3 * len(arrivals) else 0
if consecutive_bad >= 2:
breaker_open_until, consecutive_bad = t + 4, 0 # open for 4 ticks, then probe again
if t >= 26 and recovered_at is None and not rejected:
recovered_at = t
return ok, failed, sent_total, peak, recovered_at, shed
print(f"{'client policy':<22}{'succeeded':>10}{'failed':>8}{'load sent':>11}{'peak/tick':>10}{'healthy again at tick':>23}")
for policy in ("no retry", "immediate retry", "backoff + jitter", "breaker"):
ok, failed, sent, peak, rec, shed = simulate(policy)
print(f"{policy:<22}{ok:>10}{failed:>8}{sent:>11}{peak:>10}{str(rec):>23}" + (f" (shed {shed} without calling)" if shed else ""))
print(f"\ndependency fully restored at tick 26; total user demand = {DEMAND * TICKS}")client policy succeeded failed load sent peak/tick healthy again at tick
no retry 3280 320 3600 60 26
immediate retry 3377 223 5141 175 28
backoff + jitter 3502 98 4909 163 30
breaker 2941 659 3106 71 26 (shed 659 without calling)
dependency fully restored at tick 26; total user demand = 3600الـ retries ضاعفت الحمل في أسوأ وقت: الطلب الحقيقي 60 في الـ tick، والخدمة المتعبة شافت peak حوالي 3 أضعاف ده (عمود peak/tick)، وإجمالي الحمل زاد بأكتر من 40% — على خدمة طاقتها أصلًا نازلة. ده الـ retry storm، وهو السبب إن الخدمة فضلت ترفض طلبات بعد ما رجعت لكامل طاقتها عند tick 26.
Backoff + jitter أنقذ طلبات أكتر، مش «خلّص أسرع»: عدد الفشل نزل لأقل من نص الـ immediate retry، لأن الإعادات اتوزعت على وقت أطول فلقت طاقة فاضية. التمن ظاهر في العمود الأخير: ذيل الإعادات المتأخرة خلّى آخر رفض يحصل أبعد شوية. من غير jitter كل الـ clients بيرجعوا في نفس اللحظة (موجات متزامنة) — الـ jitter هو اللي بيكسر التزامن.
الـ circuit breaker بياخد قرار مختلف تمامًا: الحمل المبعوت رجع قريب من الطلب الأصلي والخدمة سليمة فور رجوع طاقتها — لكن عدد الطلبات الفاشلة هو الأعلى، لأن الـ breaker رفض مئات الطلبات من غير ما يجرّبها (shed). هو بيضحّي بنجاحات ممكنة عشان يحمي الـ dependency، ويخلّي الـ caller يرد فورًا بـ fallback بدل ما يعلّق threads على timeout.
مفيش سياسة «الأحسن»: لو الـ dependency خاصة بيك وعندك وقت تستنى: backoff. لو مشتركة بين خدمات كتير أو عندك fallback مفيد: breaker. وفي الواقع بتستخدم الاتنين مع بعض + حد أقصى صغير للمحاولات. الأرقام من نموذج مبسط (ticks، طاقة ثابتة، breaker بدائي) — خُد منها الشكل النوعي مش القيم.
التطبيق في .NET
لم يتم عمل compile لهذا الكود. الخصائص المستخدمة من Microsoft.Extensions.Http.Resilience / Polly v8 حسب التوثيق.
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri(cfg["Inventory:Url"]!))
.AddResilienceHandler("inventory", pipeline =>
{
pipeline.AddTimeout(TimeSpan.FromSeconds(6)); // 1) total budget for the whole operation
pipeline.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 2,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
Delay = TimeSpan.FromMilliseconds(200),
}); // 2) retries live INSIDE the total budget
pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.3,
MinimumThroughput = 20, // do not trip on 2 failures out of 3 calls
SamplingDuration = TimeSpan.FromSeconds(30),
BreakDuration = TimeSpan.FromSeconds(15),
}); // 3) breaker sees every individual attempt
pipeline.AddTimeout(TimeSpan.FromSeconds(2)); // 4) per-attempt timeout, innermost
});الترتيب هو التصميم: الـ timeout الإجمالي برا عشان الإعادات ما تعدّيش الميزانية. الـ breaker جوه الـ retry عشان يعدّ كل محاولة فاشلة ويقطع الإعادات لما يفتح. الـ timeout لكل محاولة أقرب حاجة للنداء. ومهم: الـ retry بس على العمليات الـ idempotent — POST بيعمل خصم من غير idempotency key ما يتعادش.
خدمة الدفع بطيئة، وكل الـ clients عندهم 5 retries فورية. إيه اللي غالبًا هيحصل؟
Circuit Breaker
Circuit breaker له Closed/ Open/ Half-Open. Closed يسمح calls ويراقب failures؛ عند threshold يفتح ويرفض calls بسرعة؛ بعد break duration يسمح probes قليلة في Half-Open؛ نجاحها يغلق الدائرة، وفشلها يعيد فتحها.
الـ breaker يحمي caller والـ dependency من cascading failure، لكنه لا يصلح dependency. Partition breakers by dependency/endpoint/tenant when appropriate. لا تجعل breaker عالميًا لخدمات غير مرتبطة. اختَر sampling window و minimum throughput و failure ratio مع مراعاة traffic volume؛ 2 failures في traffic منخفض لا تعني بالضرورة outage.
Fallback يجب أن يكون truthful: cached stale catalog ممكن، لكن لا ترجع «payment succeeded» من fallback. Circuit-open response قد يكون 503/429 حسب contract. سجّل breaker state transitions و rejected calls.
Bulkhead و Concurrency Limits
Bulkhead يقسم resources حتى لا يستهلك dependency واحدة كل threads/connections. مثال: pricing max concurrency 40، shipping 20، email 10. استخدم bounded queues و semaphores، ورفض سريع عند الامتلاء بدل queue غير محدود.
Thread pool starvation في .NET قد يحدث مع sync-over-async أو blocking calls. لا تستخدم .Result/.Wait() على async I/O. حدد MaxConnectionsPerServer عند الحاجة، DB pool budget، worker concurrency، و request body limits. Limits لازم تتناسب مع dependency capacity وليس API replicas فقط.
public sealed class PricingGate
{
private readonly SemaphoreSlim _semaphore = new(40, 40);
public async Task<T> ExecuteAsync<T>(Func<Task<T>> action, CancellationToken ct)
{
if (!await _semaphore.WaitAsync(TimeSpan.FromMilliseconds(100), ct))
throw new DependencyBusyException("Pricing capacity reached.");
try { return await action(); }
finally { _semaphore.Release(); }
}
}في multi-instance deployment، SemaphoreSlim local لكل process؛ total concurrency = replicas × limit. لو تحتاج global quota استخدم distributed coordination بحذر، أو قسّم capacity per replica مع autoscaling awareness.
Polly و .NET Resilience Pipelines
.NET resilience stack يتيح pipelines حول HttpClient أو delegates. رتب strategies بعناية: timeout يحدد حد العملية، retry يعيد transient operation، circuit breaker يوقف تكرار الفشل، rate limiter/bulkhead يحد concurrency. ترتيب wrappers يؤثر في semantics: هل timeout لكل محاولة أم لكل العملية كلها؟ هل breaker يرى كل attempt أم logical request؟ اختبر ذلك.
لا تضع retry على كل HttpClient تلقائيًا؛ صنف endpoints. GET غالبًا idempotent، لكن POST قد ينفذ command. استخدم idempotency contract. تجنب nested resilience pipelines بين gateway و service و client دون budget موحد.
builder.Services.AddHttpClient("catalog", client =>
{
client.BaseAddress = new Uri("https://catalog.internal/");
})
.AddStandardResilienceHandler(options =>
{
options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(3);
options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(1);
options.Retry.MaxRetryAttempts = 2;
});الأسماء/الخصائص الدقيقة تعتمد على Microsoft.Extensions.Http.Resilience version. راجع package docs قبل نسخ config إلى production. لا تضع total timeout أقل من مجموع attempts/backoff بشكل يجعل retries بلا معنى.
API Edge: Gateway و Rate Limiting و BFF
Edge controls: TLS, WAF, authentication validation, request size, rate/concurrency limits, IP reputation, bot protection, routing, header normalization، و DDoS protection. Gateway ليس المكان الوحيد للـ authorization؛ service يجب أن تتحقق من resource ownership والـ tenant scope.
Rate limiting strategies: fixed/sliding window، token bucket، concurrency limiter. Apply per identity/tenant/route and global safety limit. IP-based only can punish NAT users. Return 429 + Retry-After. Distinguish abuse throttling from capacity protection.
BFF يجمع data tailored to client but should avoid becoming domain orchestration hub. Service mesh مناسب عند الحاجة إلى mTLS/traffic shifting/policy across many services، لكن operational overhead substantial. لا تضف mesh لو platform team لا تستطيع تشغيله.
Rate Limiting: Fairness و Partitioning
طبّق limits على عدة مستويات: global safety limit، per-tenant quota، per-user abuse limit، per-route cost، concurrency cap. Weighted cost مفيد لو endpoint search ثقيل أكثر من GET بسيط. Burst allowance يحسن UX لكنه يجب أن يكون محدودًا.
Fairness مهمة: tenant واحد لا يستهلك كل workers. Weighted fair queuing أو per-tenant queues قد تكون مطلوبة. Rate limit response يجب أن يوضح retry policy دون كشف internal capacity. Monitor top throttled tenants، لكن لا تسجل identifiers عالية cardinality ك metric labels؛ استخدم logs/traces أو sampled dimensions.
Graceful Degradation و Load Shedding
Graceful degradation يعني تحافظ على core journey وتقلل non-critical work. مثال: checkout يظل يعمل لكن recommendations تتوقف؛ catalog يعرض cached data؛ analytics event يتأخر. Load shedding يرفض/يسقط low-priority work مبكرًا قبل انهيار النظام.
حدد priorities، admission control، queue limits، max request size، max concurrency، و per-tenant fairness. لا تقبل requests أكثر من capacity ثم تتركها تتراكم في memory. Return 503/429 مع retry guidance. لا تجعل retry-after قصيرًا لكل clients فيسبب thundering herd.
Fallbacks تحتاج freshness labels و expiry. stale price/stock لا يصلح لقرار مالي أو inventory guarantee. degraded mode يجب أن يكون explicit ومختبرًا، لا behavior مفاجئًا عند outage.
Health Checks و Readiness و Graceful Shutdown
Liveness: هل process حي ويمكن للـ orchestrator تركه يعمل؟ لا تفشل liveness لمجرد DB down وإلا قد تدخل restart loop. Readiness: هل instance قادرة حاليًا على استقبال traffic؟ Startup probe تمنح وقت initialization. Dependency checks يجب أن تكون bounded timeout وألا تسبب thundering herd على DB.
Graceful shutdown: stop accepting new requests، mark unready، drain in-flight work، stop consumers، commit/abandon leases safely، ثم exit قبل termination grace period. Background workers يجب أن يستجيبوا لـ CancellationToken.
Health endpoint لا يكشف connection strings أو exception details للعامة. افصل internal detailed health عن public minimal health. راقب readiness flapping و restart counts.
Observability و SLI/SLO/Error Budget
SLI مقياس مثل successful requests / valid requests أو p95 latency. SLO target خلال window، مثل 99.9% success over 30 days. SLA اتفاق تعاقدي وقد يرتبط credits/penalties. Error budget هو النسبة المسموحة للفشل؛ 99.9% يتيح 0.1% failure budget.
RED لل services: Rate, Errors, Duration. USE لل resources: Utilization, Saturation, Errors. Distributed tracing يربط request عبر services باستخدام trace/span context. Logs structured وتحتوي correlation/trace IDs، دون secrets/PII. Metrics ذات cardinality محدودة؛ لا تستخدم userId أو orderId ك label.
Alert على symptoms/SLO burn rate لا كل exception. Runbook يشرح impact، dashboard، mitigation، rollback، escalation، verification. Postmortem blameless يركز على contributing factors والـ system improvements.
Failure Drills و Resilience Testing
اختبر: dependency timeout، connection refused، HTTP 429/503، slow responses، DNS failure، broker unavailable، DB pool exhaustion، duplicate messages، worker crash، expired lock، و partial deploy. استخدم fault injection أو test doubles في test environment، ثم controlled experiments في staging.
لكل drill اكتب hypothesis، blast radius، abort condition، expected telemetry، recovery action، و evidence. مثال: «عند توقف recommendation service، p95 checkout لا يزيد أكثر من 50ms، ولا يزيد 5xx، ويظهر fallback counter». لا تبدأ chaos experiment في production بلا guardrails/approval.
اختبر recovery أيضًا: بعد رجوع dependency هل queue drains؟ هل retries تندفع معًا؟ هل circuit breaker half-open؟ هل stale cache يتم تحديثه؟ هل operators يعرفون replay steps؟
Incident Response و Runbook
Runbook الجيد يحدد symptom، customer impact، dashboard، recent changes، safe mitigations، rollback steps، escalation، verification، و communication owner. Incident commander يدير coordination؛ responders يحققون؛ communications owner يحدث status. لا تجعل الجميع يغير production في وقت واحد.
Mitigation أولًا ثم root cause. Feature flag off، traffic shift، scale within dependency budget، disable noncritical work، or rollback. بعد الاستقرار، postmortem blameless: timeline، detection gap، contributing conditions، what went well، actions with owner/date. لا تكتفِ بـ«developer mistake»؛ أصلح guardrails والاختبارات والـ operational design.
Idempotency في HTTP و Commands
HTTP method semantics لا تكفي وحدها. PUT مصمم ليكون idempotent من حيث النتيجة، لكن implementation قد يرسل email كل مرة إذا لم يحترم semantics. POST command قد يكون idempotent عبر Idempotency-Key. Key scope يجب أن يشمل tenant/user/operation حتى لا يتصادم مستخدمان.
احفظ request hash، status، response/result reference، created/expiry. عند duplicate key + same payload أعد النتيجة السابقة؛ عند duplicate key + different payload ارفض 409. تعامل مع concurrent first requests عبر unique constraint/atomic insert؛ لا تعتمد على memory dictionary في عدة replicas.
احتفظ key أطول من retry window المتوقع، لكن لا تخزن response حساسًا دون access control. Idempotency لا تمنع كل business duplicates إذا client يستخدم key جديدًا لكل retry؛ contract يجب أن يوضح من ينشئ key وكيف يعاد استخدامه.
Resilience لـ LLM providers: حالة خاصة
الـ LLM API dependency غريبة: latency بالثواني مش الـ milliseconds، أخطاء 429 متكررة، أحيانًا الرد بيرجع 200 بس محتواه ناقص أو مش JSON، وتكلفة كل retry فلوس حقيقية. القواعد العامة (timeouts، retries، circuit breaker) تنطبق، لكن بأرقام مختلفة.
builder.Services.AddHttpClient("llm")
.AddResilienceHandler("llm", b =>
{
b.AddTimeout(TimeSpan.FromSeconds(20)); // total, including retries
b.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 2, BackoffType = DelayBackoffType.Exponential, UseJitter = true,
ShouldRetryAfterHeader = true, // honour Retry-After on 429
ShouldHandle = a => ValueTask.FromResult(a.Outcome.Result?.StatusCode is HttpStatusCode.TooManyRequests
or >= HttpStatusCode.InternalServerError || a.Outcome.Exception is HttpRequestException)
});
b.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{ FailureRatio = 0.5, MinimumThroughput = 20, SamplingDuration = TimeSpan.FromSeconds(30), BreakDuration = TimeSpan.FromSeconds(30) });
b.AddTimeout(TimeSpan.FromSeconds(8)); // per attempt (non-streaming)
});- Streaming: الـ per-attempt timeout يقيس أول token مش الرد كله، وما تعملش retry بعد ما بدأت تبعت tokens للمستخدم (هيشوف كلام مكرر).
- Retry على 400 (context طويل، content filter) مالوش لازمة — نفس الطلب هيفشل.
- Fallback لموديل تاني لازم يكون اتعمله eval؛ fallback لموديل أضعف من غير اختبار = جودة غير معروفة.
- Validation للمحتوى: structured output بيفشل في الـ parsing؟ retry واحد بـ repair prompt، وبعدين fail بوضوح.
Load shedding و backpressure عمليًا
لما الحمل يزيد عن الـ capacity، عندك اختيارين: كل الطلبات تبطأ لحد ما كله يعمل timeout (انهيار)، أو ترفض جزء بسرعة وتخدم الباقي كويس. الـ shedding بيتعمل بالأولوية: health checks و login والدفع أولًا، والتقارير والـ exports والـ batch AI آخر حاجة.
builder.Services.AddRateLimiter(o =>
{
o.AddConcurrencyLimiter("critical", c => { c.PermitLimit = 200; c.QueueLimit = 100; });
o.AddConcurrencyLimiter("background", c => { c.PermitLimit = 20; c.QueueLimit = 0; }); // reject immediately when full
});
app.MapPost("/payments", Pay).RequireRateLimiting("critical");
app.MapPost("/reports", BuildReport).RequireRateLimiting("background");القيم دي جاية من load test (Performance)، مش تخمين: لاقي النقطة اللي الـ latency بيبدأ يقفز عندها، وحط الحد تحتها.
أخطاء شائعة
- Retries في كل طبقة (client + gateway + service + SDK) ← 3×3×3 = 27 طلب لكل طلب فاشل (retry storm).
- Timeout أطول عند الـ caller من الـ callee: الـ callee بيكمل شغل محدش مستنيه.
- Circuit breaker مشترك لكل الـ endpoints بتاعة dependency فيها endpoint واحد بايظ.
- Fallback بيرجع بيانات قديمة من غير إشارة للمستخدم أو للـ metrics.
اختبر Resilience و API Edge
هل Retry مناسب لكل 5xx؟
ما وظيفة Circuit Breaker؟
ما الفرق بين Liveness و Readiness؟
ليه SemaphoreSlim limit ليس global في عدة replicas؟
ما معنى error budget؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 15 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.