CQRS و Event Sourcing: الـ events هي الحقيقة

جارٍ التحميل…

01 / ملخص الدرس

CQRS و Event Sourcing: الـ events هي الحقيقة

اتنين سحبوا من نفس الحساب في نفس الوقت والرصيد عدّى من غير أي أثر، ومحدش يقدر يقول الرصيد كان كام امبارح، والـ dashboard بيعمل queries تقيلة على نفس الـ table اللي الـ writes شغّالة عليه. بنفهم الـ CQRS: الـ commands بتكتب، والـ queries بتقرا من read models مختلفة.

02 / شرح الدرس مكتوبًا

نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.

أهلًا بيك. بص على accounts dot naive dot js. CRUD عادي: row لكل حساب فيها الرصيد الحالي. وده اللي بنعمله في أغلب الأوقات، وهو تمام في أغلب الأوقات. بس فيه أنواع data، زي الفلوس، المشاكل دي بتبقى فيها خطيرة. الـ read وبعدين الـ write: اتنين requests قروا خمسمية، وكل واحد سحب أربعمية، والاتنين كتبوا مِيّة. تمانمية اتسحبوا من خمسمية. ده اسمه lost update. والـ UPDATE مسح الرصيد القديم. مين سحب؟ إمتى؟ ليه؟ لو عميل اشتكى، مفيش أي حاجة تقدر تبص فيها، غير logs لو ربنا سترها. والـ dashboard عايز مجاميع كل يوم، والـ admin عايز الحسابات اللي اتقفلت. queries تقيلة، على نفس الـ table، اللي الـ writes بتتقفل عليه. فيه فكرتين بيحلّوا ده، وغالبًا بيتقالوا مع بعض: CQRS و Event Sourcing.

CQRS، يعني Command Query Responsibility Segregation. اسم كبير لفكرة بسيطة: الـ model اللي بيكتب غير الـ model اللي بيقرا. الـ write side: commands زي Withdraw و Deposit. بيتأكد من الـ rules، ويكتب. ومش محتاج يبقى سهل في القراية. الـ read side: read models، tables أو indexes متفصّلة على مقاس الـ screen بالضبط. table للرصيد، وتاني للمجاميع اليومية، وممكن واحد في Elasticsearch للـ search. ومن غير JOINs تقيلة. والاتنين بيتربطوا ببعض بالـ events: كل ما الـ write side يكتب حاجة، الـ read models بتتعملها update. وده معناه eventual consistency: بعد الـ command بشوية صغيرين، الـ read model ممكن يكون لسه قديم. و Event Sourcing بيروح أبعد: بدل ما تحفظ الرصيد، تحفظ اللي حصل. AccountOpened، و MoneyDeposited خمسمية، و MoneyWithdrawn أربعمية. والرصيد مش متخزّن في أي حتة، هو بيتحسب: تبدأ من لا حاجة، وتلف على الـ events. بص على schema dot sql. events table: كل event ليه stream_id، يعني الحساب ده بتاع مين، و version جُوّه الـ stream، و position عام لكل الـ events. والـ UNIQUE على الـ stream مع الـ version هو اللي بيمنع الـ lost update. هنشوف إزاي حالًا. projection_checkpoints: كل read model واصل لحد أنهي position. والـ read models نفسهم: account_balances للـ API، و daily_totals للـ dashboard.

الـ write side في event sourcing بيتكتب كـ two functions، وده أجمل حاجة فيه: decide: بتاخد command والـ state الحالي، وترجّع events، أو ترفض بـ DomainError. هنا كل الـ business rules. evolve: بتاخد state و event، وترجّع الـ state الجديد. من غير rules خالص، لأن الـ event حصل خلاص. والاتنين pure functions، من غير database، فالـ tests بتاعتهم سهلة أوي. والـ handleCommand بيربطهم: اقرا الـ stream، واعمل fold بالـ evolve، و decide، و append. وأهم حاجة: الـ append بيقول أنا قريت لحد version اتنين، فاكتب تلاتة. لو حد تاني كتب تلاتة قبلي، الـ append بيرفض بـ WRONG_EXPECTED_VERSION. ساعتها بنقرا تاني، و decide تاني على الـ state الجديد. وده اسمه optimistic concurrency: مفيش locks وقت القراية، بس الكتابة بتتأكد.

والـ read side: الـ projections. بص على projections dot js. كل projection فيه handler لكل event type يهمه، بيعدّل الـ read model. والـ projection بيقرا الـ events من آخر position وصلها، ويطبّقها، ويعمل update للـ checkpoint، في نفس الـ transaction. كده لو وقع في النص، مفيش event اتطبّق مرتين ولا اتنسى. والأجمل: read model جديد؟ اكتب projection، وشغّله من position صفر، وهيتبني من كل الـ history. read model فيه bug؟ صلّح الـ handler، و rebuild. وكمان time travel: الرصيد كان كام عند version تلاتة؟ اعمل fold لحد تلاتة بس.

بس event sourcing مش ببلاش. الـ stream لو فيه مليون event، الـ fold هيبقى بطيء. الحل snapshots: كل ألف event تحفظ الـ state، وتبدأ منه. الـ events schema ما ينفعش تتغير بسهولة، لأن الـ events القديمة موجودة للأبد. فبتعمل versioning للـ events، أو upcasters بتحوّل القديم للجديد وقت القراية. الـ GDPR: الـ events مش بتتمسح، فالـ data الشخصية بتتعملها encryption بـ key لكل user، ولما يطلب المسح، تمسح الـ key. والأهم: الفريق كله لازم يفهم الطريقة دي. استخدمه لما الـ history نفسها قيمة: فلوس، و audit، و workflows. ومش لكل CRUD في الـ app. التحدي. عندك lab dot js، بيبدأ بالـ lost update في CRUD حقيقي، وبعدين نفس الموقف بالـ event sourcing، والـ projections، و read model جديد بيتبني من الـ history، و rebuild، و time travel. والمطلوب es dot js. كل التفاصيل في الكومنت: decide و evolve، و appendToStream بالـ expectedVersion، و readStream و loadAggregate و stateAt، و handleCommand بالـ retry، و runProjection و rebuildProjection و projectionLag. اقرا الكومنت كويس، وخصوصًا ترتيب الـ checks في الـ decide، ونشغّل test dot js لحد ما تبقى أربعتاشر من أربعتاشر.

تمرين

اكتب es.js: DomainError، و evolve و decide، و appendToStream بالـ advisory lock والـ expectedVersion، و readStream و loadAggregate و stateAt، و handleCommand بالـ retry على الـ conflict، و runProjection بالـ checkpoint في نفس الـ transaction، و rebuildProjection، و projectionLag. كل التفاصيل في الكومنت، وشغّل node test.js.

الحل. decide و evolve: switch بسيط، وكل الـ rules في decide. appendToStream: الـ advisory lock بيخلّي الـ appends ورا بعض، علشان position أكبر عمره ما يتعمله commit قبل position أصغر، وإلا الـ projection ممكن يعدّي event. ده تمن بسيط في الـ throughput، وفيه event stores بتحل المشكلة دي بطرق تانية. handleCommand: loop، والـ conflict بس هو اللي بيعمل retry. والـ projection: الـ handler والـ checkpoint في نفس الـ transaction. نشغّل lab dot js.

es.js
// es.js: الـ account كـ decide و evolve، و event store على Postgres بالـ optimistic concurrency، و projections بـ checkpoints
export class DomainError extends Error {
  constructor(code, message = code) { super(message); this.code = code; }
}

export function evolve(state, e) {
  switch (e.type) {
    case "AccountOpened": return { owner: e.data.owner, balance: 0, status: "open" };
    case "MoneyDeposited": return { ...state, balance: state.balance + e.data.amount };
    case "MoneyWithdrawn": return { ...state, balance: state.balance - e.data.amount };
    case "AccountFrozen": return { ...state, status: "frozen" };
    case "AccountUnfrozen": return { ...state, status: "open" };
    default: return state;
  }
}

export function decide(cmd, state) {
  const fail = (code) => { throw new DomainError(code); };
  if (cmd.type === "Open") {
    if (state) fail("ALREADY_OPENED");
    if (!cmd.owner) fail("INVALID_OWNER");
    return [{ type: "AccountOpened", data: { owner: cmd.owner } }];
  }
  if (!["Deposit", "Withdraw", "Freeze", "Unfreeze"].includes(cmd.type)) fail("UNKNOWN_COMMAND");
  if (!state) fail("NOT_OPENED");
  if (cmd.type === "Freeze") return state.status === "frozen" ? [] : [{ type: "AccountFrozen", data: { reason: cmd.reason ?? null } }];
  if (cmd.type === "Unfreeze") return state.status === "open" ? [] : [{ type: "AccountUnfrozen", data: {} }];
  if (!Number.isInteger(cmd.amount) || cmd.amount <= 0) fail("INVALID_AMOUNT");
  if (state.status === "frozen") fail("ACCOUNT_FROZEN");
  if (cmd.type === "Deposit") return [{ type: "MoneyDeposited", data: { amount: cmd.amount } }];
  if (state.balance < cmd.amount) fail("INSUFFICIENT_FUNDS");
  return [{ type: "MoneyWithdrawn", data: { amount: cmd.amount } }];
}

async function tx(pool, fn) {
  const c = await pool.connect();
  try { await c.query("BEGIN"); const r = await fn(c); await c.query("COMMIT"); return r; }
  catch (e) { await c.query("ROLLBACK").catch(() => {}); throw e; }
  finally { c.release(); }
}

const conflict = (streamId, expected, actual) =>
  Object.assign(new Error(`${streamId}: expected ${expected} بس الـ version ${actual}`), { code: "WRONG_EXPECTED_VERSION", expected, actual });

export async function appendToStream(pool, streamId, expectedVersion, events) {
  if (!events.length) throw new Error("مفيش events");
  try {
    return await tx(pool, async (c) => {
      // lock واحد لكل الـ appends: الـ positions بتتعمل commit بالترتيب، فالـ projection عمره ما يعدّي واحدة
      await c.query("SELECT pg_advisory_xact_lock(4242)");
      const { rows } = await c.query("SELECT coalesce(max(version), 0)::int AS v FROM events WHERE stream_id = $1", [streamId]);
      if (rows[0].v !== expectedVersion) throw conflict(streamId, expectedVersion, rows[0].v);
      let v = expectedVersion;
      for (const e of events) await c.query("INSERT INTO events (stream_id, version, type, data) VALUES ($1, $2, $3, $4)", [streamId, ++v, e.type, JSON.stringify(e.data ?? {})]);
      return v;
…

المخرجات

$ node lab.js
① CRUD: اتنين سحبوا أربعمية من حساب فيه خمسمية في نفس الوقت (read، وبعدين احسب، وبعدين write):
   النتايج: تمام و تمام ← الرصيد: 100 ← تمانمية اتسحبوا من خمسمية، ومفيش أي أثر لده

② event sourcing: نفس الموقف:
   النتايج: تمام (version 3، محاولات 1) و INSUFFICIENT_FUNDS
   الـ stream: v1 AccountOpened ← v2 MoneyDeposited 500 ← v3 MoneyWithdrawn 400

③ CQRS: الـ commands بتكتب events، والـ queries بتقرا من read model:
   سحب من حساب frozen: ACCOUNT_FROZEN
   الـ read model قبل الـ projection: 0 rows، والـ lag: 8 events
   runProjection: 8 events، والـ lag: 0
     account-mahmoud  mahmoud    100  open  v3
     account-sara     sara      1200  frozen  v3
     account-youssef  youssef    300  open  v2
   يوسف سحب خمسين، والـ read model لسه: 300 ← eventual consistency. وبعد الـ projection: 250

④ read model جديد اتعمل النهارده، وبيتبني من كل الـ history:
   dailyTotals: 9 events ← [{"deposits":2000,"withdrawals":450}]
   حد غيّر الـ read model بإيده غلط. rebuild: 9 events، ورصيد سارة رجع: 1200

⑤ time travel: رصيد محمود عند كل version:
   v1: {"owner":"mahmoud","balance":0,"status":"open"}
   v2: {"owner":"mahmoud","balance":500,"status":"open"}
   v3: {"owner":"mahmoud","
…

الأول: الـ CRUD قال تمام للاتنين، والرصيد مِيّة، يعني تمانمية اتسحبوا من خمسمية. التاني: نفس الموقف، واحد نجح، والتاني خد conflict، قرا تاني، ولقى الرصيد مِيّة، فاترفض بـ INSUFFICIENT_FUNDS. والـ stream بيحكي القصة كلها. التالت: الـ Freeze التاني ما طلّعش event. والـ read model كان فاضي قبل الـ projection، وبعده فيه التلات حسابات. ولما يوسف سحب، الـ read model فضل قديم لحد الـ projection الجاي. ده الـ eventual consistency قدامك. الرابع: read model جديد خالص اتبنى من الـ events القديمة. ولما حد غيّر الرصيد بإيده غلط، الـ rebuild رجّعه صح. والخامس: الرصيد عند كل version. والسادس: append بـ version قديم اترفض، والـ events زي ما هي. ونشغّل test dot js.

es.js

المخرجات

$ node test.js
✅ evolve: fold على كل الأنواع، والـ type المش معروف ما بيغيّرش حاجة 
✅ decide: Open و الـ codes الأساسية 
✅ decide: الفلوس، و frozen، والـ Freeze و Unfreeze من غير events لو مالهاش لازمة 
✅ appendToStream: الـ versions لكل stream، والـ position عام 
✅ appendToStream: expectedVersion غلط ← WRONG_EXPECTED_VERSION ومعاه expected و actual ومفيش حاجة اتكتبت، و events فاضية ← throw 
✅ readStream: الشكل، و fromVersion و toVersion، والـ streams التانية لأ 
✅ loadAggregate و stateAt 
✅ handleCommand: version و events و attempts، و no-op من غير append، والـ DomainError بيطلع زي ما هو 
✅ handleCommand مع بعض: كل الـ deposits دخلت بالـ retry، والسحب ما عدّاش الرصيد 
✅ handleCommand بـ retries صفر: الـ conflict بيطلع WRONG_EXPECTED_VERSION 
✅ runProjection: الـ read model، والـ checkpoint، و batchSize، والمرة التانية صفر، والـ lag 
✅ runProjection: handler وقع ← الـ batch كله اترجع والـ checkpoint ما اتحركش، وبعد الإصلاح كمّل 
✅ projection تاني على نفس الـ events: الأنواع اللي مالهاش handler بتتعدّى والـ checkpoint بيتحرك 
✅ rebuildProjection: reset و checkpoint صفر، وبيتبني تاني من الأول 

14/14

كله نجح. الـ events بقت في كل حتة: outbox، و sagas، و projections. وكل ده محتاج حاجة توصّل الـ messages بين الـ services. الدرس الجاي: الـ queues والـ brokers، BullMQ و RabbitMQ و Kafka و SQS، كل واحد بيضمن إيه، وإمتى تختار مين.

accounts.naive.js
// accounts.naive.js: CRUD عادي، الـ row فيها الرصيد الحالي وبس
import { pool } from "./db.js";

export async function withdraw(accountId, amount) {
  const { rows } = await pool.query("SELECT balance FROM accounts WHERE id = $1", [accountId]);
  if (rows[0].balance < amount) throw new Error("الرصيد مش كفاية");
  // ← بين الـ SELECT والـ UPDATE، request تاني ممكن يكون قرا نفس الرصيد
  await pool.query("UPDATE accounts SET balance = $1 WHERE id = $2", [rows[0].balance - amount, accountId]);
  // ← والرصيد القديم راح. مين سحب؟ إمتى؟ ليه؟ مفيش
}

// وصفحة الـ admin عايزة: مجموع الإيداعات كل يوم، و الحسابات اللي اتقفلت الشهر ده
// ← كل واحدة query تقيلة على نفس الـ table اللي الـ writes شغّالة عليه
schema.sql
-- schema.sql: الـ event store هو الحقيقة، والباقي read models بتتبني منه
DROP TABLE IF EXISTS events, projection_checkpoints, account_balances, daily_totals;

CREATE TABLE events (
  position   bigserial PRIMARY KEY,           -- ترتيب عام لكل الـ events
  stream_id  text  NOT NULL,                  -- الـ aggregate، زي account-mahmoud
  version    int   NOT NULL,                  -- ترتيب جُوّه الـ stream: واحد، اتنين، تلاتة
  type       text  NOT NULL,
  data       jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (stream_id, version)                 -- مستحيل اتنين يكتبوا نفس الـ version
);

CREATE TABLE projection_checkpoints (
  name     text PRIMARY KEY,
  position bigint NOT NULL DEFAULT 0
);

-- read model للـ API: رصيد كل حساب في row واحدة
CREATE TABLE account_balances (
  account_id text PRIMARY KEY,
  owner      text NOT NULL,
  balance    int  NOT NULL,
  status     text NOT NULL,
  version    int  NOT NULL
);

-- read model للـ dashboard: مجموع كل يوم
CREATE TABLE daily_totals (
  day         date PRIMARY KEY,
  deposits    int NOT NULL DEFAULT 0,
  withdrawals int NOT NULL DEFAULT 0
);
db.js
// db.js: الـ pool، و reset بيشغّل schema.sql من الأول
import pg from "pg";
import { readFileSync } from "node:fs";

export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
export const reset = () => pool.query(readFileSync(new URL("./schema.sql", import.meta.url), "utf8"));
export const count = async (sql, params = []) => Number((await pool.query(sql, params)).rows[0].n);
projections.js
// projections.js: كل projection عبارة عن handlers لكل event type، و reset بيفضّي الـ read model بتاعه
export const balances = {
  name: "balances",
  reset: (c) => c.query("TRUNCATE account_balances"),
  handlers: {
    AccountOpened: (c, e) => c.query("INSERT INTO account_balances VALUES ($1, $2, 0, 'open', $3)", [e.streamId, e.data.owner, e.version]),
    MoneyDeposited: (c, e) => c.query("UPDATE account_balances SET balance = balance + $2, version = $3 WHERE account_id = $1", [e.streamId, e.data.amount, e.version]),
    MoneyWithdrawn: (c, e) => c.query("UPDATE account_balances SET balance = balance - $2, version = $3 WHERE account_id = $1", [e.streamId, e.data.amount, e.version]),
    AccountFrozen: (c, e) => c.query("UPDATE account_balances SET status = 'frozen', version = $2 WHERE account_id = $1", [e.streamId, e.version]),
    AccountUnfrozen: (c, e) => c.query("UPDATE account_balances SET status = 'open', version = $2 WHERE account_id = $1", [e.streamId, e.version]),
  },
};

const bump = (col) => (c, e) => c.query(
  `INSERT INTO daily_totals (day, ${col}) VALUES ($1::timestamptz::date, $2)
   ON CONFLICT (day) DO UPDATE SET ${col} = daily_totals.${col} + EXCLUDED.${col}`,
  [e.createdAt, e.data.amount],
);

export const dailyTotals = {
  name: "daily-totals",
  reset: (c) => c.query("TRUNCATE daily_totals"),
  handlers: { MoneyDeposited: bump("deposits"), MoneyWithdrawn: bump("withdrawals") },
};
lab.js
// lab.js: CRUD بيضيّع update، وبعدين event sourcing و CQRS على Postgres حقيقي
import { pool, reset, count } from "./db.js";
import { handleCommand, readStream, loadAggregate, stateAt, runProjection, rebuildProjection, projectionLag, appendToStream } from "./es.js";
import { balances, dailyTotals } from "./projections.js";

await reset();
console.log("① CRUD: اتنين سحبوا أربعمية من حساب فيه خمسمية في نفس الوقت (read، وبعدين احسب، وبعدين write):");
await pool.query("DROP TABLE IF EXISTS crud_accounts; CREATE TABLE crud_accounts (id text PRIMARY KEY, balance int NOT NULL); INSERT INTO crud_accounts VALUES ('a', 500)");
const crudWithdraw = async (amount) => {
  const { rows } = await pool.query("SELECT balance FROM crud_accounts WHERE id = 'a'");
  await new Promise((r) => setTimeout(r, 20));
  if (rows[0].balance < amount) return "رفض";
  await pool.query("UPDATE crud_accounts SET balance = $1 WHERE id = 'a'", [rows[0].balance - amount]);
  return "تمام";
};
console.log("   النتايج:", (await Promise.all([crudWithdraw(400), crudWithdraw(400)])).join(" و "), "← الرصيد:", await count("SELECT balance n FROM crud_accounts"), "← تمانمية اتسحبوا من خمسمية، ومفيش أي أثر لده");

console.log("\n② event sourcing: نفس الموقف:");
const A = "account-mahmoud";
await handleCommand(pool, A, { type: "Open", owner: "mahmoud" });
await handleCommand(pool, A, { type: "Deposit", amount: 500 });
const res = await Promise.allSettled([handleCommand(pool, A, { type: "Withdraw", amount: 400 }), handleCommand(pool, A, { type: "Withdraw", amount: 400 })]);
console.log("   النتايج:", res.map((r) => (r.status === "fulfilled" ? `تمام (version ${r.value.version}، محاولات ${r.value.attempts})` : r.reason.code)).join(" و "));
console.log("   الـ stream:", (await readStream(pool, A)).map((e) => `v${e.version} ${e.type}${e.data.amount ? " " + e.data.amount : ""}`).join(" ← "));

console.log("\n③ CQRS: الـ commands بتكتب events، والـ queries بتقرا من read model:");
for (const [id, owner] of [["account-sara", "sara"], ["account-youssef", "youssef"]]) await handleCommand(pool, id, { type: "Open", owner });
await handleCommand(pool, "account-sara", { type: "Deposit", amount: 1200 });
await handleCommand(pool, "account-youssef", { type: "Deposit", amount: 300 });
await handleCommand(pool, "account-sara", { type: "Freeze", reason: "مراجعة" });
await handleCommand(pool, "account-sara", { type: "Freeze", reason: "تاني" });
try { await handleCommand(pool, "account-sara", { type: "Withdraw", amount: 100 }); } catch (e) { console.log("   سحب من حساب frozen:", e.code); }
console.log("   الـ read model قبل الـ projection:", await count("SELECT count(*) n FROM account_balances"), "rows، والـ lag:", await projectionLag(pool, "balances"), "events");
console.log("   runProjection:", await runProjection(pool, balances, { batchSize: 3 }), "events، والـ lag:", await projectionLag(pool, "balances"));
for (const r of (await pool.query("SELECT * FROM account_balances ORDER BY account_id")).rows) console.lo
…
03 / دروس المسار (122)
  1. 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
  2. 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
  3. 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
  4. 04القيم والمتغيرات والأنواع: const و let و typeof
  5. 05القرارات والتكرار: if و === والـ truthy والـ loops
  6. 06الـ functions: parameters و return والـ arrow functions والـ scope
  7. 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
  8. 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
  9. 09الـ callbacks والـ closures وأول لمسة async: setTimeout
  10. 10الـ classes والـ errors: throw و try/catch و stack trace
  11. 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
  12. 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
  13. 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
  14. 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
  15. 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
  16. 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
  17. 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
  18. 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
  19. 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
  20. 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
  21. 21الـ Node test runner والـ debugging: tests من غير مكتبات
  22. 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
  23. 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
  24. 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
  25. 25الـ Middleware ودورة حياة الـ request جُوّه Express
  26. 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
  27. 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
  28. 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
  29. 29رفع الملفات وحدود الحجم: multer من غير ثغرات
  30. 30الـ Realtime: Server-Sent Events و WebSockets
  31. 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
  32. 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
  33. 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
  34. 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
  35. 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
  36. 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
  37. 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
  38. 38Partial و Covering indexes: indexes أصغر وأسرع
  39. 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
  40. 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
  41. 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
  42. 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
  43. 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
  44. 44الـ Locks والـ Deadlocks: مين مستني مين
  45. 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
  46. 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
  47. 47Migrations من غير downtime: expand و backfill و contract
  48. 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
  49. 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
  50. 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
  51. 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
  52. 52Cache-aside والـ TTL: Redis قدام الـ database
  53. 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
  54. 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
  55. 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
  56. 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
  57. 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
  58. 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
  59. 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
  60. 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
  61. 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
  62. 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
  63. 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
  64. 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
  65. 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
  66. 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
  67. 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
  68. 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
  69. 69الـ MFA والـ recovery: التاني factor اللي بجد
  70. 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
  71. 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
  72. 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
  73. 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
  74. 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
  75. 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
  76. 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
  77. 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
  78. 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
  79. 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
  80. 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
  81. 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
  82. 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
  83. 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
  84. 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
  85. 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
  86. 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
  87. 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
  88. 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
  89. 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
  90. 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
  91. 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
  92. 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
  93. 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
  94. 94Docker Volumes: الـ data بتتحفَظ فين
  95. 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
  96. 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
  97. 97Reverse Proxy و TLS: اللي واقف قدام الـ app
  98. 98Multi-arch Images والـ Native Modules: اشتغلت عندي
  99. 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
  100. 100Kubernetes من الأول: Pods و Deployments و Services و Probes
  101. 101Modular Monolith و DDD: حدود واضحة من غير network
  102. 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
  103. 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
  104. 104CQRS و Event Sourcing: الـ events هي الحقيقةانت هنا
  105. 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
  106. 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
  107. 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
  108. 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
  109. 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
  110. 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
  111. 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
  112. 112ORM ولا SQL: query builders و repositories و migrations و transactions
  113. 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
  114. 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
  115. 115Contract Testing و Property-Based Testing بـ fast-check
  116. 116الـ Payments: idempotency و webhooks و refunds و reconciliation
  117. 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
  118. 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
  119. 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
  120. 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
  121. 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
  122. 122Incident Runbooks: من الـ alert للـ postmortem