الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
حساب تقيل في route واحد بيخلّي أي request تاني يستنى ربع تانية. بنعمل CPU profile بـ node --cpu-prof ونقرا الـ flame graph (self و total والـ inlining)، ونصلّح الـ algorithm الأول، وبعدين worker threads و pool بعدد الـ cores بـ queue ليها حد و timeout، و libuv thread pool، والفرق بين worker و child process و cluster. والتحدي: cpu.js قصاد تلاتة وعشرين حالة.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. الدرس اللي فات قسّمنا الشغل لدفعات علشان ما يقفلش الـ event loop. بس ده عدل، مش سرعة: لسه core واحدة بتعمل كل حاجة. النهارده الشغل الـ CPU بجد. primes dot js بيعد الـ prime numbers لحد رقم معين. فيه نسختين: countPrimes بيجرّب كل رقم لحد الرقم نفسه، و countPrimesFast بيجرّب لحد الـ square root بس. server dot js بيستخدم النسخة البطيئة جُوّه الـ route، على الـ event loop. و load dot js زي الدرس اللي فات: أربع requests تقيلة، و user تاني بيطلب fast كل عشرين ملي تانية. نشغّل.
// load.js: أربع requests تقيلة مع بعض، و user تاني بيطلب fast كل عشرين ms
const B = "http://localhost:3000";
const t = async (p) => { const s = performance.now(); const r = await fetch(B + p); const body = await r.json(); return { ms: performance.now() - s, body }; };
await t("/fast"); // warm-up
const heavy = Array.from({ length: 4 }, () => t("/primes?n=40000"));
const fast = [];
for (let i = 0; i < 30; i++) { fast.push(t("/fast")); await new Promise((r) => setTimeout(r, 20)); }
const hs = await Promise.all(heavy);
const fs = (await Promise.all(fast)).map((x) => x.ms).sort((a, b) => a - b);
console.log(`primes: ${hs.map((h) => h.body.count).join("، ")} ← الأربعة خلصوا في ${Math.max(...hs.map((h) => h.ms)).toFixed(0)}ms`);
console.log(`fast: p50 ${fs[Math.floor(fs.length / 2)].toFixed(0)}ms | max ${fs.at(-1).toFixed(0)}ms`);المخرجات
$ node server.js & S=$!; sleep 1; node load.js; kill $S on 3000 primes: 4203، 4203، 4203، 4203 ← الأربعة خلصوا في 584ms fast: p50 271ms | max 586ms
الأربعة خلصوا في أكتر من نص تانية، لأنهم اشتغلوا ورا بعض على core واحدة. والـ fast الـ p50 بتاعه ربع تانية تقريبًا. نفس مشكلة الدرس اللي فات. بس قبل ما نفكر في threads، أول سؤال: الوقت ده رايح فين بالضبط؟ لأن أغلب الوقت الحل مش إنك تزوّد cores، الحل إنك تشيل الشغل اللي مالوش لازمة. bench dot js بيشغّل الحسبة مرة بالنسختين، علشان نقارن ونعمل profile بعد شوية. نشغّل.
// bench.js: بنشغّل الشغل التقيل مرة، علشان نعمله profile
import { countPrimes, countPrimesFast } from "./primes.js";
let t = performance.now();
const a = countPrimes(40000);
console.log(`countPrimes(40000) = ${a} في ${(performance.now() - t).toFixed(0)}ms`);
t = performance.now();
const b = countPrimesFast(40000);
console.log(`countPrimesFast(40000) = ${b} في ${(performance.now() - t).toFixed(1)}ms`);المخرجات
$ node bench.js countPrimes(40000) = 4203 في 142ms countPrimesFast(40000) = 4203 في 2.5ms
نفس النتيجة بالضبط، بس النسخة البطيئة أبطأ خمسين مرة تقريبًا. ولا عدد threads هيعمل كده. وده الترتيب الصح دايمًا: الأول قيس، وبعدين صلّح الـ algorithm أو الـ query، وفي الآخر خالص فكّر في parallelism. وإزاي تقيس في app كبير مش عارف فيه مين البطيء؟ CPU profile. node dash dash cpu-prof بيسجّل وإنت شغّال: كل ملي تانية تقريبًا بيبص الـ stack فيه إيه، ولما الـ process يقفل يكتب ملف cpuprofile. تفتحه في Chrome DevTools أو في VS Code، أو بـ dash dash inspect وإنت شغّال، أو بأدوات زي clinic flame و zero x. وهتشوف flame graph: كل bar هو function، اللي تحته هو اللي ناداها، وعرض الـ bar هو الوقت. total: الوقت جُوّه الـ function واللي نادتهم كلهم. ده عرض الـ bar. self: الوقت جُوّه الـ function نفسها بس. الـ bars العريضة اللي مفيش حاجة كتير فوقها، دي اللي بتدوّر عليها. وفي production: ما تشغّلش profiler طول الوقت. شغّله دقيقة على instance واحدة لما الـ metrics تقول فيه مشكلة.
طيب لو الشغل CPU فعلًا ومحتاجه: worker threads. الـ worker thread ده V8 تاني جُوّه نفس الـ process، ليه event loop لوحده و memory لوحده. بيكلّم الـ main thread بـ postMessage. والـ data اللي بتتبعت بتتنسخ، بـ structured clone. فلو بتبعت array فيها مليون حاجة، النسخ نفسه ليه تمن. ولو عايز من غير نسخ: transfer لـ ArrayBuffer، أو SharedArrayBuffer. عمل worker جديد بياخد عشرات الملي تانية و memory. علشان كده ما تعملش worker لكل request. اعمل pool من الأول، بعدد الـ cores، بـ availableParallelism. وفيه حاجتين تانيين بيتلخبطوا مع بعض: child process: process كامل لوحده. أتقل، بس مناسب لو هتشغّل برنامج تاني أو code مش ضامنه. cluster: أكتر من نسخة من الـ server كله على نفس الـ port. ده لتوزيع الـ requests، مش للشغل التقيل. وفي containers غالبًا بتعمل أكتر من container بدل cluster. وكمان Node عنده libuv thread pool، أربع threads بالـ default. الـ crypto pbkdf2 و scrypt العاديين، مش الـ Sync، والـ zlib، والـ fs، و dns lookup، كلهم بيشتغلوا هناك. فلو عندك hashing كتير للـ passwords، ممكن الطابور يبقى هناك، وتزوّده بـ UV underscore THREADPOOL underscore SIZE.
والـ pool نفسه لازم يكون فيه تلات حاجات: queue ليها حد. لو كل الـ workers مشغولين، الـ task تستنى. بس لو الطابور طول أوي، ارفض على طول بـ five oh three و Retry-After، زي الـ load shedding. لأن request هيستنى عشر تواني، المستخدم أصلًا مشي. timeout. لو task وقعت في loop ما بتخلصش، الـ worker ده ضاع. والجميل إن worker terminate بيقتله حتى وهو جُوّه الـ loop، حاجة ما تقدرش تعملها في الـ main thread. اقتله، واعمل واحد جديد مكانه. errors: لو الـ worker رمى error، يرجع للـ request ده بس، والـ pool يكمّل. وفي الشغل الحقيقي فيه مكتبة اسمها piscina بتعمل ده كله. بس النهارده هنكتبه بإيدينا علشان نفهمه. server dot js الجديد: pool بعدد الـ cores، و maxQueue تمانية، و timeout تانيتين. والـ route بيرجّع five oh three لو الـ queue مليانة، و five oh four لو timeout. و primes-worker dot js بيستقبل الـ task ويرد. و top dot js بيقرا آخر profile ويطبع أعلى خمس functions. التحدي: اكتب cpu dot js. test dot js فيه تلاتة وعشرين حالة.
cpu.js: createPool بـ workers بعدد معروف من الأول، و queue بحد بترجع queue full، و timeout بيعمل terminate ويبدّل الـ worker، و stats و close. و topFunctions بيحسب self و total من الـ samples والـ timeDeltas ويرتّب.
الحل. الـ pool: array للـ workers الفاضيين، و queue، و Map من كل worker للـ task اللي شغّال عليها. dispatch بيوصّل الاتنين ببعض. replace بيستخدمه الـ timeout والـ error: reject، و terminate، و worker جديد. topFunctions: Map للـ parent من الـ children، وكل sample بيتضاف لـ self بتاع الـ node نفسه، ولـ total بتاع كل اللي فوقه، مع Set علشان الـ recursion ما تتحسبش مرتين. نعمل profile لـ bench dot js، ونقراه بـ top dot js.
// cpu.js: worker pool للشغل التقيل، و قراية CPU profile
import { Worker } from "node:worker_threads";
import { availableParallelism } from "node:os";
export function createPool(file, { size = availableParallelism(), maxQueue = 100, timeoutMs = 5000 } = {}) {
const idle = [], queue = [], current = new Map(); // worker ← task شغّال عليه
let closed = false, nextId = 0;
const spawn = () => {
const w = new Worker(file);
w.on("message", ({ id, result, error }) => {
const t = current.get(w);
if (!t || t.id !== id) return;
finish(w, t);
error ? t.reject(new Error(error)) : t.resolve(result);
idle.push(w);
dispatch();
});
w.on("error", (e) => replace(w, e)); // crash جُوّه الـ worker
idle.push(w);
};
const finish = (w, t) => { clearTimeout(t.timer); current.delete(w); };
const replace = (w, err) => {
const t = current.get(w);
if (t) { finish(w, t); t.reject(err); }
const i = idle.indexOf(w);
if (i >= 0) idle.splice(i, 1);
w.terminate();
if (!closed) { spawn(); dispatch(); }
};
const dispatch = () => {
while (idle.length && queue.length) {
const w = idle.pop(), t = queue.shift();
t.timer = setTimeout(() => replace(w, new Error("timeout")), timeoutMs);
current.set(w, t);
w.postMessage({ id: t.id, data: t.data });
}
};
for (let i = 0; i < size; i++) spawn();
return {
run(data) {
if (closed) return Promise.reject(new Error("pool closed"));
if (!idle.length && queue.length >= maxQueue) return Promise.reject(new Error("queue full")); // backpressure
return new Promise((resolve, reject) => {
queue.push({ id: ++nextId, data, resolve, reject });
dispatch();
});
},
stats: () => ({ size, busy: current.size, queued: queue.length }),
async close() {
closed = true;
for (const t of queue.splice(0)) t.reject(new Error("pool closed"));
const workers = [...idle, ...current.keys()];
for (const [w, t] of current) { finish(w, t); t.reject(new Error("pool closed")); }
await Promise.all(workers.map((w) => w.terminate()));
idle.length = 0;
},
};
}
// CPU profile (من node --cpu-prof): مين أكل الوقت؟
// self = الوقت جُوّه الـ function نفسها. total = هي واللي نادتهم (عرض الـ bar في الـ flame graph)
export function topFunctions(profile, { n = 5, by = "self" } = {}) {
const byId = new Map(profile.nodes.map((nd) => [nd.id, nd]));
const parent = new Map();
for (const nd of profile.nodes) for (const c of nd.children ?? []) parent.set(c, nd.id);
const key = (nd) => { const f = nd.callFrame; return `${f.functionName || "(anonymous)"} ${(f.url || "").split("/").pop()}:${f.lineNumber + 1}`; };
const rows = new Map();
const row = (k) => rows.get(k) ?? rows.set(k, { name: k, selfMs: 0, totalMs: 0 }).get(k);
let all = 0;
profile.samples.forEach((id, i) => {
const ms = (profile.timeDeltas[i] ?? 0) / 1000; // microseconds ← ms
all += ms;
…المخرجات
$ rm -rf prof; node --cpu-prof --cpu-prof-dir=prof bench.js && node top.js
countPrimes(40000) = 4203 في 144ms
countPrimesFast(40000) = 4203 في 2.5ms
أعلى خمسة بالـ self:
84.1% self 143ms total 143ms countPrimes primes.js:7
6.4% self 11ms total 11ms (program) :0
2.6% self 4ms total 4ms (idle) :0
1.9% self 3ms total 5ms compileForInternalLoader realm:383
0.7% self 1ms total 1ms wrappedFn errors:537
أعلى خمسة بالـ total:
100.0% self 0ms total 170ms (root) :0
87.2% self 0ms total 149ms (anonymous) bench.js:1
87.2% self 0ms total 149ms evaluate :0
87.2% self 0ms total 149ms run module_job:419
84.1% self 143ms total 143ms countPrimes primes.js:7بالـ self: countPrimes واخدة أغلب الوقت. بس استنى، الـ loop التقيلة في isPrime، مش countPrimes. ليه isPrime مش باينة؟ لأن V8 لما لقى function صغيرة بتتنادى كتير، حطها جُوّه اللي بيناديها، ده اسمه inlining. فالـ profile بيوريك الوقت في الـ caller. خليها في دماغك وإنت بتقرا أي flame graph. و countPrimesFast حوالي اتنين في المِيّة بس. بالـ total: الـ root فوق بمِيّة في المِيّة، وبعدها الـ module نفسه، وبعدها countPrimes. ده الـ stack من فوق لتحت، زي الـ flame graph بالضبط. ونشغّل الـ load على الـ server الجديد.
المخرجات
$ node server.js & S=$!; sleep 1; node load.js; kill $S on 3000 primes: 4203، 4203، 4203، 4203 ← الأربعة خلصوا في 345ms fast: p50 1ms | max 10ms
الـ fast رجع ملي تانية، وأبطأ واحد كام ملي تانية بس. الـ event loop فاضي تمامًا، لأن الشغل كله في الـ workers. والأربعة خلصوا أسرع من الأول، لأن عندنا اتنين cores، فاتنين بيشتغلوا مع بعض. على machine فيها تمانية cores الفرق هيبقى أكبر. ونشغّل test dot js.
المخرجات
$ node server.js & S=$!; sleep 1; node test.js; kill $S on 3000 ✅ self: b أول واحد بخمسة ms ✅ self: a اتنين، و main نص ms ✅ percent من الوقت الكلي ✅ function من غير اسم ← (anonymous) ✅ total: root فوق بتمانية، وبعده main بسبعة ونص ✅ recursion: b الـ total بتاعه خمسة مش تمانية ✅ profile حقيقي: أكتر function أكلت وقت countPrimes countPrimes primes.js:7 ✅ pool: countPrimes لمية ← خمسة وعشرين ✅ stats: الاتنين busy ✅ اتنين مع بعض على اتنين workers أسرع من ورا بعض واحد 141ms، اتنين مع بعض 146ms ✅ worker بيرمي error ← reject بنفس الرسالة ✅ وبعدها الـ pool لسه شغّال ✅ بعد close ← pool closed ✅ maxQueue: التالت ← queue full على طول ✅ stats: واحد busy وواحد queued ✅ task ما بتخلصش ← timeout ✅ الـ worker اتبدّل، واللي كان مستني خلص ✅ close بيرفض الشغّال واللي مستني ✅ server: primes لألف ← مية تمانية وستين ✅ server: fast سريع وقت الشغل التقيل أبطأ واحد 6ms ✅ server: worker بيرمي ← 500 ✅ server: task ما بتخلصش ← 504 ✅ server: وبعدها لسه شغّال 23/23 نجحوا
كله نجح. وخلي بالك من الترتيب: الـ profile قال لنا إن المشكلة في الـ algorithm، والـ fast version أسرع خمسين مرة. الـ workers بيكمّلوا، مش بيعوّضوا. الدرس الجاي: الـ memory. الـ heap و الـ GC، وإزاي تلاقي memory leak بـ heap snapshots قبل ما الـ process يقع بـ out of memory.
// server.js: الشغل التقيل في worker pool، والـ event loop فاضي للباقيين
import express from "express";
import { availableParallelism } from "node:os";
import { createPool } from "./cpu.js";
const pool = createPool(new URL("./primes-worker.js", import.meta.url), { size: availableParallelism(), maxQueue: 8, timeoutMs: 2000 });
const app = express();
app.get("/fast", (req, res) => res.json({ ok: true }));
app.get("/stats", (req, res) => res.json(pool.stats()));
app.get("/primes", async (req, res) => {
const n = Math.min(Number(req.query.n ?? 40000), 100000);
const data = req.query.op ? { op: req.query.op } : { n }; // op للمعمل بس: throw و forever
try {
res.json({ n, count: await pool.run(data) });
} catch (e) {
if (e.message === "queue full") return res.set("Retry-After", "1").status(503).json({ error: e.message });
if (e.message === "timeout") return res.status(504).json({ error: e.message });
res.status(500).json({ error: e.message });
}
});
const server = app.listen(3000, () => console.log("on 3000"));
process.on("SIGTERM", () => server.close(() => pool.close()));// primes.js: شغل CPU حقيقي، من غير أي I/O
export function isPrime(x) {
if (x < 2) return false;
for (let d = 2; d < x; d++) if (x % d === 0) return false; // بيجرّب كل الأرقام لحد x
return true;
}
export function countPrimes(n) {
let c = 0;
for (let i = 0; i < n; i++) if (isPrime(i)) c++;
return c;
}
// نفس النتيجة، بس بيجرّب لحد الجذر التربيعي بس
export function isPrimeFast(x) {
if (x < 2) return false;
for (let d = 2; d * d <= x; d++) if (x % d === 0) return false;
return true;
}
export function countPrimesFast(n) {
let c = 0;
for (let i = 0; i < n; i++) if (isPrimeFast(i)) c++;
return c;
}// primes-worker.js: بيشتغل في thread لوحده. بياخد { id, data } ويرجّع { id, result } أو { id, error }
import { parentPort } from "node:worker_threads";
import { countPrimes } from "./primes.js";
parentPort.on("message", ({ id, data }) => {
try {
if (data.op === "throw") throw new Error("bad input");
if (data.op === "forever") for (;;); // للمعمل: task ما بتخلصش
parentPort.postMessage({ id, result: countPrimes(data.n) });
} catch (e) {
parentPort.postMessage({ id, error: e.message });
}
});// top.js: بيقرا آخر profile ويطبع أكتر functions أكلت وقت
import { readdirSync, readFileSync } from "node:fs";
import { topFunctions } from "./cpu.js";
const f = readdirSync("prof").filter((x) => x.endsWith(".cpuprofile")).sort().pop();
const p = JSON.parse(readFileSync(`prof/${f}`, "utf8"));
for (const by of ["self", "total"]) {
console.log(`\nأعلى خمسة بالـ ${by}:`);
for (const r of topFunctions(p, { n: 5, by })) console.log(` ${r.percent.toFixed(1).padStart(5)}% self ${r.selfMs.toFixed(0).padStart(4)}ms total ${r.totalMs.toFixed(0).padStart(4)}ms ${r.name}`);
}import { spawnSync } from "node:child_process";
import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { createPool, topFunctions } from "./cpu.js";
let ok = 0, all = 0;
const check = (name, cond, extra = "") => { all++; if (cond) ok++; console.log(cond ? "✅" : "❌", name, extra); };
const near = (a, b) => Math.abs(a - b) < 1e-6;
const err = (p) => p.then(() => "no error", (e) => e.message);
const B = "http://localhost:3000";
const fr = (id, name, line, children) => ({ id, callFrame: { functionName: name, url: "file:///app/x.js", lineNumber: line - 1 }, children });
const prof = {
nodes: [fr(1, "(root)", 0, [2, 6]), fr(2, "main", 1, [3, 4]), fr(3, "a", 5), fr(4, "b", 9, [5]), fr(5, "b", 9), fr(6, "", 20)],
samples: [3, 3, 4, 5, 2, 6], timeDeltas: [1000, 1000, 2000, 3000, 500, 500],
};
const self = topFunctions(prof);
check("self: b أول واحد بخمسة ms", self[0].name === "b x.js:9" && near(self[0].selfMs, 5));
check("self: a اتنين، و main نص ms", near(self.find((r) => r.name === "a x.js:5").selfMs, 2) && near(self.find((r) => r.name === "main x.js:1").selfMs, 0.5));
check("percent من الوقت الكلي", near(self[0].percent, (5 / 8) * 100));
check("function من غير اسم ← (anonymous)", self.some((r) => r.name === "(anonymous) x.js:20"));
const tot = topFunctions(prof, { by: "total", n: 2 });
check("total: root فوق بتمانية، وبعده main بسبعة ونص", tot.length === 2 && tot[0].name.startsWith("(root)") && near(tot[0].totalMs, 8) && near(tot[1].totalMs, 7.5));
check("recursion: b الـ total بتاعه خمسة مش تمانية", near(topFunctions(prof, { by: "total", n: 9 }).find((r) => r.name === "b x.js:9").totalMs, 5));
const dir = mkdtempSync(`${tmpdir()}/prof-`);
spawnSync(process.execPath, ["--cpu-prof", `--cpu-prof-dir=${dir}`, "bench.js"]);
const real = topFunctions(JSON.parse(readFileSync(`${dir}/${readdirSync(dir)[0]}`, "utf8")), { n: 1 });
check("profile حقيقي: أكتر function أكلت وقت countPrimes", real[0]?.name.startsWith("countPrimes primes.js"), real[0]?.name);
const W = new URL("./primes-worker.js", import.meta.url);
const pool = createPool(W, { size: 2, maxQueue: 4, timeoutMs: 1000 });
check("pool: countPrimes لمية ← خمسة وعشرين", (await pool.run({ n: 100 })) === 25);
let s = performance.now();
await pool.run({ n: 40000 });
const one = performance.now() - s;
s = performance.now();
const two = pool.run({ n: 40000 }), three = pool.run({ n: 40000 });
await new Promise((r) => setTimeout(r, 10));
check("stats: الاتنين busy", pool.stats().busy === 2 && pool.stats().size === 2);
await Promise.all([two, three]);
const par = performance.now() - s;
check("اتنين مع بعض على اتنين workers أسرع من ورا بعض", par < one * 1.6, `واحد ${one.toFixed(0)}ms، اتنين مع بعض ${par.toFixed(0)}ms`);
check("worker بيرمي error ← reject بنفس الرسالة", (await err(pool.run({ op: "throw" }))) === "bad input");
check("وبعدها الـ pool لسه شغّال", (await pool.run({ n: 10 })) === 4);
await pool.close();
check("بعد close ← pool closed", (await e
…03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فينانت هنا
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem