منهج ثابت لحل أي System Design Question
ابدأ بتوضيح المطلوب والـ scope، ثم اكتب functional/non-functional requirements. اسأل عن scale و regions و latency و consistency و retention والـ failure tolerance. لا تقفز إلى components قبل معرفة constraints.
بعدها قدّر traffic/storage/bandwidth. صمم API و data model. ارسم high-level architecture مع critical flows. اختر أهم bottleneck أو risk واعمل deep dive. اختم trade-offs، failure handling، security، observability، rollout و cost. المقابلة ليست مسابقة أسماء technologies؛ هي اختبار طريقة التفكير.
1. Clarify scope and assumptions
2. Functional + non-functional requirements
3. Traffic / storage / bandwidth estimates
4. API contracts and data model
5. High-level architecture
6. Deep dive: bottlenecks and consistency
7. Reliability, security, observability
8. Trade-offs, cost, evolution planاكتب assumptions على السبورة. لو interviewer غير assumption، حدّث التصميم بدل الدفاع عن رسم سابق. اعرض البدائل وسبب الاختيار.
منهج الـ system design في رسمة
Case 1: URL Shortener
Requirements: create short link، redirect بسرعة، optional expiry/custom alias، owner analytics، abuse prevention. Read-heavy: كل short URL قد يُفتح آلاف المرات. Redirect latency أهم من dashboard analytics.
API: POST /links ينشئ، GET /{code} يحول، GET /links/{id}/analytics يعرض stats. Data: code unique، destination URL، owner، created/expiry، status. Unique index على code ضروري. لا تعتمد على random collision من غير retry/unique constraint.
Code generation: sequence + Base62 يعطي compact deterministic IDs لكنه يكشف growth/order. Random 7–10 chars يقلل predictability لكن يحتاج collision check. Custom aliases تحتاج reserved words/abuse controls. Redirect use 301 vs 302: 301 قد يُcache بقوة ويصعب تغيير destination؛ 302/307 أكثر مرونة حسب semantics.
Architecture: API → DB for writes; Redis cache for code→URL; CDN/edge only إذا invalidation/security policy واضحة; event stream for click analytics asynchronously. لا تضع analytics write في redirect critical path. Rate-limit creation and scan for phishing/malware. Prevent open redirect abuse through policy/abuse reporting, not by blindly blocking all external URLs.
Case 2: Distributed Rate Limiter
Fixed window: counter لكل key/window، سهل لكنه يسمح burst على boundary (100 request آخر ثانية ثم 100 أول ثانية جديدة). Sliding log دقيق لكنه يخزن timestamps كثيرة. Sliding counter approximate يقلل memory. Token bucket يسمح burst محددًا بمعدل refill ثابت. Leaky bucket ينعّم output rate.
حدد key: user ID/API key/IP/tenant/route، مع priority و cost units. لا تعتمد IP فقط خلف proxy أو في NAT. استخدم trusted forwarded headers. Distributed implementation يحتاج atomic operation (Redis Lua/script أو atomic DB operation) لتجنب race conditions. Decide fail-open vs fail-closed عند cache failure حسب endpoint risk.
capacity = 20 tokens
refill = 5 tokens / second
request cost = 1 token
on request:
elapsed = now - last_refill
tokens = min(capacity, tokens + elapsed * refill)
if tokens >= request_cost:
tokens -= request_cost
ALLOW
else:
REJECT with Retry-After ~= (request_cost - tokens) / refillHeaders: RateLimit-Limit/RateLimit-Remaining/Retry-After حسب standard/product contract. راقب rejected rate و hot keys و Redis latency. لا تكشف وجود account عبر rate-limit response.
Case Study متنفذ: Rate Limiter — أربع خوارزميات تحت نفس الهجوم
«حد 100 request في الدقيقة» جملة واضحة، لكن تنفيذها له أربع طرق مشهورة بتدّي نتايج مختلفة على نفس الـ traffic. الـ case study ده بيشغّلهم على 3 أنماط: client ملتزم، burst على حدود النافذة، و client بيبعت دفعة واحدة كبيرة.
from collections import deque
LIMIT, WINDOW = 100, 60.0
class FixedWindow:
def __init__(self): self.window, self.count = None, 0
def allow(self, t):
w = int(t // WINDOW)
if w != self.window: self.window, self.count = w, 0 # counter resets at the boundary
if self.count < LIMIT: self.count += 1; return True
return False
memory = "1 counter"
class SlidingLog:
def __init__(self): self.log = deque()
def allow(self, t):
while self.log and self.log[0] <= t - WINDOW: self.log.popleft()
if len(self.log) < LIMIT: self.log.append(t); return True
return False
memory = "1 timestamp per request (up to LIMIT)"
class SlidingCounter:
"""Weighted blend of the previous and current fixed windows: near-exact, constant memory."""
def __init__(self): self.window, self.cur, self.prev = None, 0, 0
def allow(self, t):
w = int(t // WINDOW)
if w != self.window:
self.prev = self.cur if self.window is not None and w == self.window + 1 else 0
self.window, self.cur = w, 0
overlap = 1 - (t % WINDOW) / WINDOW # share of the previous window still "in view"
if self.prev * overlap + self.cur < LIMIT: self.cur += 1; return True
return False
memory = "2 counters"
class TokenBucket:
def __init__(self, burst=LIMIT): self.capacity, self.tokens, self.last = burst, float(burst), 0.0
def allow(self, t):
self.tokens = min(self.capacity, self.tokens + (t - self.last) * LIMIT / WINDOW); self.last = t
if self.tokens >= 1: self.tokens -= 1; return True
return False
memory = "1 float + 1 timestamp"
def worst_minute(times):
"""Largest number of ACCEPTED requests inside any rolling 60-second span."""
best, q = 0, deque()
for t in times:
q.append(t)
while q[0] <= t - WINDOW: q.popleft()
best = max(best, len(q))
return best
PATTERNS = {
"steady 1.5/s for 3 min": [i / 1.5 for i in range(270)],
"burst across window boundary": [59.0 + i * 0.005 for i in range(100)] + [60.0 + i * 0.005 for i in range(100)],
"one burst of 300 at t=10": [10.0 + i * 0.001 for i in range(300)],
}
ALGOS = {"fixed window": FixedWindow, "sliding log": SlidingLog, "sliding counter": SlidingCounter, "token bucket": TokenBucket,
"token bucket (burst 20)": lambda: TokenBucket(burst=20)}
for pname, times in PATTERNS.items():
print(f"{pname} ({len(times)} requests)")
for aname, make in ALGOS.items():
limiter = make()
accepted = [t for t in times if limiter.allow(t)]
w = worst_minute(accepted)
print(f" {aname:<24} accepted={len(accepted):>3} worst rolling minute={w:>3} {'<-- far over the limit' if w > LIMIT * 1.05 else ''}")
print("\nmemory per client:")
for aname, make in list(ALGOS.items())[:4]:
print(f" {aname:<24} {make.memory}")steady 1.5/s for 3 min (270 requests)
fixed window accepted=270 worst rolling minute= 91
sliding log accepted=270 worst rolling minute= 91
sliding counter accepted=270 worst rolling minute= 91
token bucket accepted=270 worst rolling minute= 91
token bucket (burst 20) accepted=270 worst rolling minute= 91
burst across window boundary (200 requests)
fixed window accepted=200 worst rolling minute=200 <-- far over the limit
sliding log accepted=100 worst rolling minute=100
sliding counter accepted=101 worst rolling minute=101
token bucket accepted=102 worst rolling minute=102
token bucket (burst 20) accepted= 22 worst rolling minute= 22
one burst of 300 at t=10 (300 requests)
fixed window accepted=100 worst rolling minute=100
sliding log accepted=100 worst rolling minute=100
sliding counter accepted=100 worst rolling minute=100
token bucket accepted=100 worst rolling minute=100
token bucket (burst 20) accepted= 20 worst rolling minute= 20
memory per client:
fixed window 1 counter
sliding log 1 timestamp per request (up to LIMIT)
sliding counter 2 counters
token bucket 1 float + 1 timestampالـ fixed window سرّب ضعف الحد: 100 طلب في آخر ثانية من نافذة و100 في أول ثانية من اللي بعدها = 200 طلب في ثانيتين، والعدّاد شايف إن كل نافذة «في الحد». ده عيبه المعروف، وهو مقبول لو الحد للحماية التقريبية مش للفوترة.
الـ sliding log دقيق تمامًا (100 بالظبط) وتمنه ذاكرة: timestamp لكل طلب لكل client. الـ sliding counter عدّى 101 — تقريب بخطأ 1% بعدّادين بس، وعشان كده هو الاختيار الشائع في الأنظمة الكبيرة. والـ token bucket عدّى 102 لأن الـ bucket اتملى شوية خلال ثانية الـ burst نفسها.
الـ token bucket بيجاوب على سؤال تاني: «مسموح بـ burst قد إيه؟». بـ burst = 100 بيسمح بالـ 100 مرة واحدة ثم بمعدل ثابت. بـ burst = 20 بيفرد الطلبات: في الدفعة الواحدة قبل 20 بس. ده اللي بتستخدمه لما هدفك حماية خدمة وراك من الـ spikes، مش مجرد عدّ.
من خوارزمية لنظام موزع
| القرار | الاختيارات | الـ trade-off |
|---|---|---|
| مكان العدّاد | ذاكرة كل instance / Redis مشترك | المحلي أسرع لكن الحد الفعلي = الحد × عدد الـ instances؛ المشترك دقيق وبيضيف network hop ونقطة فشل |
| الـ atomicity | INCR + EXPIRE / Lua script | read-then-write من غير atomicity = race بين instanceين بيعدّوا الاتنين |
| لما Redis يقع | fail open (اسمح) / fail closed (ارفض) | open بيحافظ على الـ availability وبيشيل الحماية؛ closed العكس. قرار product مش تقني |
| مفتاح الحد | IP / user / API key / tenant | الـ IP بيظلم المستخدمين ورا NAT وبيتلفّ عليه؛ الهوية المتحقق منها أدق |
| الرد | 429 + Retry-After | من غير Retry-After الـ clients هيعيدوا فورًا ويزوّدوا الحمل |
الـ middleware الجاهز (Microsoft.AspNetCore.RateLimiting) فيه الأربع أنواع: fixed window، sliding window، token bucket، و concurrency — لكنه in-memory لكل instance. لحد مشترك بين instances محتاج store خارجي. التفاصيل في درس الـ Rate Limiting في المجال 05.
عندك 8 instances وكل واحد بيطبق حد 100/دقيقة في ذاكرته. الحد الفعلي لـ client واحد؟
Case 3: Notification System
Notifications قد تكون email/SMS/push/in-app. افصل intent عن provider: NotificationRequested event يحمل recipient reference، template key، locale، correlation ID. Notification service يقرأ preferences/consent، يطبق quiet hours، يختار channel، ثم يرسل عبر provider adapter.
لا ترسل داخل request path. Persist notification state: Pending → Processing → Sent/Failed/Suppressed. Use outbox from business transaction if notification must not be lost. Idempotency key يمنع إنشاء نفس logical notification مرتين. Provider response لا يعني أن المستخدم قرأ الرسالة؛ delivery receipts separate state.
Retries فقط للأخطاء transient، مع provider-specific quota/backoff. Permanent invalid address لا يعاد للأبد. DLQ للـ poison payloads، replay tool مع authorization/audit. Secrets في Key Vault/secret manager. لا تسجل message body أو phone/email كاملة في logs إلا وفق privacy policy.
Case 4: Chat / Real-Time Messaging
Chat يحتاج WebSocket/SignalR connections، authentication، conversation membership، durable message store، sequence/order strategy، offline delivery، read receipts، attachments، moderation، retention. لا تخلط connection server مع source of truth؛ connection قد تنقطع في أي لحظة.
Message write: validate membership → assign message ID/sequence → persist → publish event → fan-out to online recipients. Use per-conversation ordering (sequence/partition key) rather than global total ordering. Reconnect clients with cursor/last-seen sequence and fetch missed messages. Delivery ACK means delivered to client connection, not necessarily read.
Scale-out SignalR يحتاج backplane/managed service أو partitioned connection ownership. Attachments go to object storage using short-lived signed URLs, malware scan, size/type limits. Presence is ephemeral and approximate; don't treat online indicator as transactional fact.
Case 5: File Upload and Storage
للملفات الكبيرة، لا تمرر bytes عبر API server إلا لو عندك سبب. API تنشئ upload session وتصدر pre-signed URL أو chunk instructions؛ client يرفع مباشرة إلى object/blob storage. بعد upload، event يطلق malware scan/metadata extraction/transcoding. لا تعتبر الملف published قبل scan/status completion.
Data model: FileId، owner/tenant، object key، size، content type detected server-side، checksum، status، retention، created time. Use random object keys؛ لا تستخدم filename كمسار موثوق. Validate magic bytes، enforce quotas، scan malware، strip dangerous metadata حسب use case، و serve downloads عبر authorization + short-lived URL.
Resumable multipart upload يقلل إعادة رفع ملف ضخم عند انقطاع الشبكة. Cleanup abandoned uploads و orphan objects. Lifecycle policies تنقل/archive/delete حسب retention. CDN cache للملفات العامة فقط؛ private file URLs تحتاج short expiry and authorization.
Case 6: News Feed
Feed له authors/followers/posts/ranking. Fan-out on write ينسخ post references إلى inbox followers وقت النشر؛ قراءة سريعة لكن celebrity accounts ذات ملايين followers تسبب write amplification. Fan-out on read يجمع posts من followed authors عند القراءة؛ write cheap لكن read expensive.
Hybrid: fan-out on write للـ normal users، و fan-out on read للحسابات الضخمة، ثم merge/rank. خزّن references وليس copies كاملة لتقليل duplication، مع cache للـ feed pages. Use cursor pagination based on stable ordering (createdAt + ID), not OFFSET. Ranking service يجب أن يكون bounded latency مع fallback.
Delete/privacy changes تحتاج propagation؛ لا تعتمد على cached feed indefinitely. Use tombstones/versioning and authorization at read time for sensitive content. Track freshness and feed generation lag.
Case Study: News Feed — Fan-out on Write ولا on Read؟ بالحساب
import random
random.seed(1)
USERS = 1_000_000
POSTS_PER_USER_PER_DAY, FEED_READS_PER_USER_PER_DAY, FOLLOWS_PER_USER = 2, 20, 200
DAY = 86_400
# follower counts are heavy-tailed: most accounts have few followers, a handful have millions
sample = sorted((min(int(random.paretovariate(1.2) * 60), 5_000_000) for _ in range(100_000)), reverse=True)
avg_followers = sum(sample) / len(sample)
print(f"follower distribution: median={sample[len(sample) // 2]} mean={avg_followers:,.0f} max={sample[0]:,}")
for cut in (1_000, 10_000, 100_000):
print(f" accounts above {cut:>7,} followers: {sum(1 for f in sample if f > cut) / len(sample):6.2%} of accounts, {sum(f for f in sample if f > cut) / sum(sample):4.0%} of all follow edges")
print()
posts_s = USERS * POSTS_PER_USER_PER_DAY / DAY
reads_s = USERS * FEED_READS_PER_USER_PER_DAY / DAY
print(f"{'strategy':<30}{'write ops/s':>13}{'read ops/s':>12}{'worst single post':>20}{'lookups per feed open':>23}")
print(f"{'fan-out on write (push)':<30}{posts_s * avg_followers:>13,.0f}{reads_s:>12,.0f}{sample[0]:>20,}{1:>23}")
print(f"{'fan-out on read (pull)':<30}{posts_s:>13,.0f}{reads_s * FOLLOWS_PER_USER:>12,.0f}{1:>20,}{FOLLOWS_PER_USER:>23}")
for cut in (100_000, 10_000, 1_000): # hybrid: push for accounts below the cut, pull for those above it
edge_share = sum(f for f in sample if f > cut) / sum(sample) # share of follow edges that point at "celebrities"
pulled = FOLLOWS_PER_USER * edge_share # celebrity accounts in an average follow list
writes = posts_s * avg_followers * (1 - edge_share)
reads = reads_s * (1 + pulled)
print(f"{'hybrid, celebrity > ' + format(cut, ','):<30}{writes:>13,.0f}{reads:>12,.0f}{cut:>20,}{1 + pulled:>23.0f}")follower distribution: median=106 mean=335 max=1,067,113
accounts above 1,000 followers: 3.52% of accounts, 54% of all follow edges
accounts above 10,000 followers: 0.23% of accounts, 30% of all follow edges
accounts above 100,000 followers: 0.02% of accounts, 16% of all follow edges
strategy write ops/s read ops/s worst single post lookups per feed open
fan-out on write (push) 7,751 231 1,067,113 1
fan-out on read (pull) 23 46,296 1 200
hybrid, celebrity > 100,000 6,547 7,419 100,000 32
hybrid, celebrity > 10,000 5,390 14,335 10,000 62
hybrid, celebrity > 1,000 3,570 25,206 1,000 109Fan-out on write (push): القراءة أرخص حاجة ممكنة (قائمة جاهزة، lookup واحد)، والتمن كله عند الكتابة. العيب في عمود worst single post: حساب بمليون متابع ينشر = مليون كتابة لـ post واحد، والمتابعين بيشوفوه بتأخير، والـ queue بتتزحم على الباقي.
Fan-out on read (pull): الكتابة تافهة، وكل فتح للـ feed = 200 lookup ودمج. القراءة أكتر من الكتابة بعشر مرات، فده أغلى في الإجمالي وأبطأ للمستخدم في كل مرة.
الـ hybrid مش «الأحسن» — هو dial: push للحسابات تحت حد معيّن و pull للي فوقه. كل ما الحد ينزل، أسوأ حالة كتابة بتتحدد (العمود الرابع) والكتابة الإجمالية بتقل، لكن شغل القراءة بيزيد. عند حد 100,000: أسوأ post اتقص من مليون لـ 100 ألف كتابة، والتمن 32 lookup بدل 1 عند القراءة. اختيار الحد بيعتمد على إيه اللي بيوجعك أكتر: تأخير الـ feed وقت النشر ولا latency فتح الـ feed.
الدرس العام: بص على أول سطور الـ output — أقل من ربع في المية من الحسابات عليها 30% من علاقات المتابعة. التوزيع غير المتساوي هو اللي بيحدد التصميم مش المتوسط؛ تصميم مبني على «متوسط 335 متابع» كان هيقع عند أول حساب كبير.
حدود النموذج: بيعدّ عمليات مش تكلفتها الفعلية (كتابة في Redis list مش زي query بـ merge)، وبيتجاهل الـ ranking والـ caching والمستخدمين غير النشطين (اللي ما يستاهلوش push أصلًا).
cache بـ TTL ثابت 10 دقايق، وكل 10 دقايق بالظبط الـ database بيتخنق لثواني. أنهي تغييرين بيحلوا المشكلة؟
Case Study متنفذ: Caching — حجم الـ Cache، الـ Stampede، والـ TTL
«نحط cache» قرار سهل. الأسئلة الصعبة: حجمه قد إيه؟ وإيه اللي بيحصل للـ database لحظة ما المفتاح الأشهر ينتهي؟ الـ lab ده بيجاوب بالقياس على workload واقعي: قلة من المفاتيح عليها أغلب الطلبات (Zipf).
import random
from collections import OrderedDict
random.seed(3)
# ---------- 1) how big does the cache need to be? ----------
N_KEYS = 100_000
weights = [1 / (rank ** 1.0) for rank in range(1, N_KEYS + 1)] # Zipf: key #1 is asked ~N times more than key #N
requests = random.choices(range(N_KEYS), weights=weights, k=300_000)
def lru_hit_ratio(capacity):
cache, hits = OrderedDict(), 0
for k in requests:
if k in cache:
hits += 1; cache.move_to_end(k)
else:
cache[k] = True
if len(cache) > capacity:
cache.popitem(last=False) # evict the least recently used
return hits / len(requests)
print("LRU cache on Zipf-distributed traffic over 100,000 distinct keys:")
print(f"{'cache size':>12}{'% of keys':>11}{'hit ratio':>11}{'DB load vs no cache':>21}")
for cap in (100, 1_000, 10_000, 50_000):
h = lru_hit_ratio(cap)
print(f"{cap:>12,}{cap / N_KEYS:>11.1%}{h:>11.1%}{1 - h:>21.1%}")
# ---------- 2) stampede: a hot key expires while 200 requests/second are asking for it ----------
def stampede(protection, seconds=10, rps=200, ttl=5.0, rebuild_time=0.4):
"""Counts expensive rebuilds that hit the database and the worst number running at the same time."""
cached_until, in_flight, db_calls, worst = 0.0, [], 0, 0
for i in range(seconds * rps):
t = i / rps
for done in [x for x in in_flight if x <= t]:
cached_until = max(cached_until, done + ttl) # the value only becomes visible when a rebuild FINISHES
in_flight = [x for x in in_flight if x > t]
if t < cached_until:
continue # cache hit
if protection == "single-flight" and in_flight:
continue # someone is already rebuilding: wait for their result
db_calls += 1; in_flight.append(t + rebuild_time); worst = max(worst, len(in_flight))
return db_calls, worst
print("\none hot key, 200 req/s, TTL 5 s, rebuild takes 400 ms, observed for 10 s:")
for p in ("none", "single-flight"):
calls, worst = stampede(p)
print(f" protection={p:<14} database rebuilds={calls:>4} worst concurrent rebuilds={worst}")
# ---------- 3) many keys cached at the same moment expire at the same moment ----------
def expiry_spike(jitter):
ttl = 300
expiries = [ttl + (random.uniform(-jitter, jitter) * ttl) for _ in range(50_000)] # all written during one warm-up
buckets = {}
for e in expiries:
buckets[int(e)] = buckets.get(int(e), 0) + 1
return max(buckets.values())
print("\n50,000 keys warmed together, TTL 300 s — worst single second of simultaneous expiries:")
for j in (0.0, 0.1, 0.3):
print(f" TTL jitter ±{j:.0%}: {expiry_spike(j):>6,} keys expire in the same second")LRU cache on Zipf-distributed traffic over 100,000 distinct keys:
cache size % of keys hit ratio DB load vs no cache
100 0.1% 28.9% 71.1%
1,000 1.0% 50.6% 49.4%
10,000 10.0% 72.9% 27.1%
50,000 50.0% 84.0% 16.0%
one hot key, 200 req/s, TTL 5 s, rebuild takes 400 ms, observed for 10 s:
protection=none database rebuilds= 160 worst concurrent rebuilds=80
protection=single-flight database rebuilds= 2 worst concurrent rebuilds=1
50,000 keys warmed together, TTL 300 s — worst single second of simultaneous expiries:
TTL jitter ±0%: 50,000 keys expire in the same second
TTL jitter ±10%: 894 keys expire in the same second
TTL jitter ±30%: 321 keys expire in the same second1) الحجم: مع توزيع Zipf، cache بـ 1% من المفاتيح بيخدم نسبة كبيرة من الطلبات، وكل مضاعفة بعد كده بتجيب عائد أقل. ده معناه إن الـ cache مش لازم يشيل كل حاجة — لازم يشيل الـ hot set. وعمود DB load هو المهم: الفرق بين 70% و90% hit ratio مش «20 نقطة»، ده الحمل على الـ database بينزل للتلت.
2) الـ stampede: لحظة انتهاء المفتاح، كل الطلبات اللي جاية في الـ 400ms بتلاقيه مش موجود وكلها بتروح تبنيه. من غير حماية الـ database بياخد عشرات النداءات المتزامنة لنفس الـ query الغالية — وده بيحصل كل TTL. بالـ single-flight (واحد بس يبني والباقي يستنى أو ياخد القيمة القديمة) بيبقى نداء واحد لكل انتهاء. في .NET ده اللي HybridCache بيعمله جاهز.
3) الـ jitter: مفاتيح اتكتبت مع بعض (warm-up أو deploy) بتنتهي مع بعض. إضافة عشوائية صغيرة للـ TTL بتفرد الانتهاء على وقت أطول وبتحوّل الـ spike لحمل مسطّح.
Case 7: E-commerce Checkout and Inventory
Checkout يجمع cart validation، price snapshot، stock reservation، payment authorization، order creation، confirmation. السعر لا يؤخذ من client. Inventory concurrency أهم نقطة: لا تستخدم read-then-write بدون concurrency control؛ طلبان قد يريان quantity=1 ويبيعان الاثنين.
Atomic conditional update: UPDATE Inventory SET Available = Available - @q WHERE ProductId=@id AND Available >= @q ثم تحقق من affected rows. أو optimistic concurrency rowversion، أو reservation records مع expiry. Reservation state: Held → Confirmed/Released/Expired. TTL cleanup لا يكون مصدر الحقيقة الوحيد؛ enforce expiry in transaction.
Payment provider call خارج DB transaction الطويلة. استخدم idempotency key، store provider reference، reconcile ambiguous timeouts by querying provider/webhook. Webhooks verify signature and deduplicate event ID. Order status workflow explicit; never mark Paid based on client redirect alone.
UPDATE dbo.Inventory
SET AvailableQuantity = AvailableQuantity - @quantity
WHERE ProductId = @productId
AND AvailableQuantity >= @quantity;
IF @@ROWCOUNT = 0
THROW 50001, 'Insufficient stock', 1;في scale أكبر، partition inventory by SKU/warehouse، queue hot SKU operations، أو reserve per bucket؛ لكن correctness first. ضع compensation: payment authorized but stock unavailable → void/refund according to provider capabilities.
Case 8: Booking and Double-Booking Prevention
المطلوب: slot لا يحجزه شخصان. لا يكفي check availability ثم insert؛ requests متزامنة قد تمر من check معًا. اجعل database constraint/transaction هو authority. لو slot discrete، unique constraint على ResourceId + SlotStart. لو intervals متداخلة، تحتاج locking/serializable strategy أو model يحول availability إلى slots ثابتة.
Reservation lifecycle: Held with expiry → Confirmed → Cancelled/Expired. Hold creation atomic، payment deadline واضحة، expiry worker يعيد تحرير السعة، وال confirm operation يتحقق أن hold ما زال صالحًا. Idempotency يمنع double submit من نفس user. استخدم UTC داخليًا، واحتفظ timezone identifier للعرض والـ DST rules.
Distributed lock وحده لا يكفي كضمان نهائي بسبب lease expiry/clock/network partitions؛ database constraint أو conditional write يظل invariant boundary. اختبر concurrency بمئات requests لنفس slot.
Case 9–10: Autocomplete و Document Q&A at Scale
Autocomplete: prefix index/trie/search engine، normalized tokens، popularity score، locale، typo tolerance، bounded top N، privacy filtering. لا تضرب primary DB لكل keypress؛ debounce في client، min query length، cache hot prefixes، rate limit. Update index asynchronously من product/catalog events.
Document Q&A/RAG: ingestion pipeline (upload → parse → OCR → chunk → metadata/ACL → embeddings → vector index). Query pipeline (authenticate → retrieve authorized chunks → rerank → construct prompt → LLM → citations). لا تعتمد على vector similarity وحدها؛ enforce tenant/document ACL قبل إرجاع chunks. Version documents and embeddings; delete must propagate to vector index and caches.
Scale knobs: batch embedding, queue workers, index partitions, hybrid lexical+vector search, reranking budget, model rate limits, token budget, caching safe deterministic query outputs. Monitor retrieval recall, citation correctness, latency/cost per query, و prompt injection attempts in retrieved content.
Case 11–12: Idempotent Payments و Job Scheduler
Payment command needs client idempotency key + server-side unique record + provider idempotency support + webhook deduplication + reconciliation. State machine should distinguish Created, Submitted, Authorized, Captured, Failed, Unknown/PendingReconciliation, Refunded. Ambiguous timeout enters Unknown, not Failed automatically.
Job scheduler stores durable schedule and next run time, claims jobs with leases, supports retry policy, misfire policy, time zones, cancellation, و distributed ownership. Use unique occurrence ID to avoid duplicate run. For recurring jobs, compute next occurrence using calendar/timezone semantics; 24 hours is not always «same local time tomorrow» across DST.
Long-running job uses heartbeat/lease renewal and checkpointing. A crashed worker's lease expires, another worker resumes; handlers must be idempotent. Expose job status/progress and operator controls with audit log.
تصميم API و Data Model في المقابلة
API design يجب أن يوضح resource identity، pagination، filtering، error contract، authentication، idempotency، و concurrency. استخدم stable IDs، لا تكشف DB schema مباشرة. للـ commands استخدم POST/PUT/PATCH semantics بوضوح، وارجع 202 للعمليات غير المتزامنة مع status URL.
Data model يحدد invariants والـ indexes. لكل query رئيسية اسأل: ما predicate؟ ما sort؟ ما cardinality؟ هل تحتاج covering index؟ هل data tenant-scoped؟ هل هناك unique constraints؟ لا تبدأ بعدد الجداول فقط؛ ابدأ بال access patterns.
POST /api/v1/orders
Authorization: Bearer ...
Idempotency-Key: 5a4b...
Content-Type: application/json
{
"items": [{ "productId": "...", "quantity": 2 }],
"shippingAddressId": "..."
}
202 Accepted
Location: /api/v1/orders/{orderId}
{ "orderId": "...", "status": "PendingPayment" }لا تضع price النهائي في request باعتباره موثوقًا. Server يعيد حساب الأسعار والضرائب/discounts ويخزن snapshot للـ order. استخدم If-Match/ETag أو rowversion عند الحاجة لمنع lost updates.
URL Shortener: تفاصيل السعة والـ Cache
لو 100 مليون redirect/day، average ≈ 1,157 RPS؛ peak factor 5 يجعل peak ≈ 5,800 RPS. إذا response metadata 1 KB، bandwidth payload ≈ 5.8 MB/s عند peak. Cache hit ratio 95% يخفض DB lookups إلى نحو 290 RPS peak، لكنه لا يخفض redirect traffic نفسه.
Code lookup cache key يجب أن يكون normalized، TTL مرتبط بال expiry، و negative caching بحذر حتى لا تمنع newly-created link. Cache invalidation عند link disable/delete ضرورية للأمان. Redirect endpoint يجب أن يتحقق من disabled/expired semantics؛ CDN cache طويلة قد تستمر بعد abuse takedown.
Analytics event لا يحمل PII غير لازم. IP address قد يكون personal data؛ اعمل truncation/retention/consent حسب policy. Bot traffic قد يشوه counts؛ analytics pipeline يجب أن يميز human/bot تقريبًا.
Chat: Fan-out و Presence و Ordering
Partition messages by ConversationId لتحقيق ordering per conversation. MessageId globally unique، و sequence per conversation يعطي stable pagination. Client reconnect يرسل lastAckedSequence؛ server يعيد missed messages من durable store. لا تعتمد على in-memory connection state وحده.
Presence ephemeral ويمكن تخزينه مع TTL/heartbeat؛ انقطاع مفاجئ يعني expiry لا explicit logout. Typing indicators لا تحتاج durable event log. Read receipts قد تكون coalesced لتقليل writes. Attachments تُرفع إلى object storage، والـ chat message يحمل reference فقط.
Group chat fan-out: small groups يمكن push لكل connection، large groups تحتاج pub/sub/partitioning. Offline delivery قد يستخدم per-user inbox أو fetch-on-open. Rate limit messages، scan links/files، و moderate abuse. End-to-end encryption يغير search/moderation/recovery trade-offs.
Booking: نموذج Slot و Concurrency
لو slots ثابتة 30 دقيقة، جدول Slot(ResourceId, StartsAtUtc, Status, ReservationId) مع unique(ResourceId, StartsAtUtc) يمنع duplicate slot row. Hold operation transaction تتحقق من availability وتحدث status بشرط Available. عند التأكيد، update بشرط Held و ExpiresAtUtc > SYSUTCDATETIME(). affected rows=0 يعني conflict/expired.
لو booking intervals arbitrary، منع overlap أصعب. SQL Server قد يستخدم serializable range locks مع index مناسب أو تصميم slot allocation. PostgreSQL exclusion constraints خيار آخر. لا تفترض أن EF Core concurrency token وحده يمنع كل overlapping interval cases.
Payment flow يحتاج saga: hold slot → authorize payment → confirm reservation؛ لو payment فشل release hold. Webhook متأخر بعد انتهاء hold يجب أن يدخل reconciliation/compensation، لا يعيد تأكيد slot تم بيعه لعميل آخر.
RAG at Scale: Isolation و Evaluation
Chunking strategy تعتمد document structure؛ chunk صغير يفتقد context، والكبير يرفع token cost ويقلل retrieval precision. Store documentId, tenantId, ACL, version, page/section, checksum, embeddingModelVersion. عند re-embedding، استخدم index versioning و gradual cutover.
Retrieval evaluation: recall@k، precision@k، MRR/nDCG، answer faithfulness، citation correctness، abstention quality. Test queries تمثل real users and adversarial cases. لا تقيس جودة RAG بـ LLM answer score فقط؛ افصل retrieval failure عن generation failure.
Prompt injection في documents: تعامل مع retrieved text كـ untrusted data، لا كتعليمات system. لا تسمح للـ retrieved content بتجاوز authorization أو تشغيل tools دون policy. Tool calls تحتاج scoped permissions and confirmation where destructive.
Case Studies: أسئلة مراجعة
ليه ما نعملش analytics synchronously في URL redirect؟
إيه الذي يمنع overselling فعليًا؟
هل payment timeout يعني فشل؟
إزاي تمنع double booking؟
ليه RAG retrieval لازم يطبق ACL؟
في أي case، اختم بتحديد أكبر bottleneck، consistency model، failure behavior، security controls، و metric ستراقبها بعد الإطلاق.
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 12 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.