الـ Payments: idempotency و webhooks و refunds و reconciliation

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

01 / ملخص الدرس

الـ Payments: idempotency و webhooks و refunds و reconciliation

عميل اتخصم منه مرتين لأنه داس Pay مرتين، و orders اتعلّمت مدفوعة لأن حد كتب status success في الـ URL، و webhook مزوّر شحن order ببلاش، و payment_failed اتأخر وقلب order مدفوع لـ failed، واتنين admins رجّعوا لنفس العميل أكتر من اللي دفعه.

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

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

أهلًا بيك. النهارده الفلوس. بص على checkout dot naive dot js. checkout بيعمل payment intent عند الـ provider، زي Stripe أو Paymob. وصفحة return بيرجع عليها العميل بعد الدفع. و webhook بيستقبل من الـ provider. و endpoint للـ refund. أربع routes، وكل واحدة فيها مشكلة بتكلّف فلوس. العميل داس Pay مرتين، أو الـ network بطيء والـ browser عمل retry: اتنين intents، واتخصم مرتين. الـ total مِيّة وأربعتاشر وعشرة قروش، مضروب في مِيّة، في الـ floats بيطلع رقم بكسور، يا الـ provider يرفضه يا يتقرّب غلط. صفحة الـ return: أي حد يكتب status بـ success في الـ URL، الـ order يتعلّم مدفوع من غير ما يدفع. الـ webhook: مفيش signature، فأي حد يبعت succeeded. ومفيش حماية من التكرار، والـ provider بيعيد الـ webhooks، فالـ order بيتشحن مرتين. ولو payment_failed قديم وصل بعد succeeded، الـ payment يرجع failed. والـ refund: مفيش حد أقصى، ومفيش idempotency، واتنين admins في نفس الوقت رجّعوا المبلغ مرتين.

تعالى نفهم الدفع بيمشي إزاي. الـ server بتاعك بيعمل payment intent عند الـ provider: أنا عايز أحصّل المبلغ ده، بالـ currency دي، للـ order ده. والـ provider بيرجّع id و client secret. العميل بيدفع على صفحة الـ provider، أو في form جاي من الـ provider جُوّه صفحتك. رقم الـ card ما بيعدّيش على الـ server بتاعك خالص، وده اللي بيخليك برّه أغلب متطلبات PCI DSS. ما تستقبلش أرقام كروت بنفسك أبدًا. وممكن البنك يطلب تأكيد زيادة، زي OTP أو 3D Secure، وده ممكن ياخد دقايق. وفي الآخر، الـ provider بيبلّغك بالنتيجة في webhook: succeeded أو failed. والـ redirect اللي العميل بيرجع بيه؟ ده للـ user experience بس. اعرض صفحة استنى شوية، بس ما تعلّمش حاجة مدفوعة منه. العميل ممكن يقفل الـ browser قبل الـ redirect، وممكن يزوّره.

الفلوس نفسها. أي مبلغ، خزّنه integer بأصغر وحدة: قروش، أو cents. مِيّة وأربعتاشر جنيه وعشرة قروش يبقى أحداشر ألف وأربعمية وعشرة. ما تخزّنش float، وما تحسبش بـ float، لأن صفر وواحد زائد صفر واتنين في الـ floats مش صفر وتلاتة بالضبط، وده شفناه في الدرس اللي فات. وخزّن الـ currency جنب المبلغ دايمًا. وخلي بالك إن مش كل الـ currencies ليها رقمين بعد العلامة: الين الياباني مالوش، وفيه currencies ليها تلاتة. فالـ conversion للعرض بيتعمل حسب الـ currency. وأي حساب، زي الخصم والضريبة وتقسيم المبلغ، بالـ integers وبقاعدة تقريب واضحة، زي splitMoney.

أول خط دفاع: الـ idempotency. العميل داس مرتين، أو الـ request الأولاني وصل للـ provider واتعمل، بس الـ response ضاع في الطريق. احنا مش عارفين حصل ولا لأ. لو عملنا retry عادي، ممكن نعمل intent تاني. الحل على مستويين: عندنا: payment واحد لكل order، بـ unique على order_id. أي request لنفس الـ order يلاقي نفس الـ row. وعند الـ provider: كل POST معاه idempotency key. والـ key ده مش random، ده مربوط بالعملية: checkout و الـ order id. فلو اتبعت تاني، حتى من request تاني في نفس الوقت، الـ provider يرجّع نفس الـ intent من غير ما يعمل جديد. والترتيب مهم: الأول نكتب الـ row عندنا بـ status creating والـ key، وبعدين نكلّم الـ provider. فلو وقعنا في النص، الـ retry يلاقي الـ row ويبعت نفس الـ key.

الـ webhooks، وفيها تلات مشاكل. الأولى: مين اللي باعت؟ الـ endpoint public. فالـ provider بيوقّع كل webhook بـ HMAC بـ secret بينكم، على الـ timestamp والـ raw body زي ما هو، قبل أي JSON parse. وانت تتأكد من الـ signature بـ timingSafeEqual، وترفض لو الـ timestamp قديم، علشان الـ replay. التانية: التكرار. الـ provider بيعمل retry لحد ما ترد بـ ميتين. ولو ردّك اتأخر أو ضاع، هيبعت تاني. فبتسجّل الـ event id في table بـ primary key، في نفس الـ transaction اللي بتعمل فيها الشغل. لو الـ insert ما دخلش، يبقى اتعمل قبل كده. التالتة: الترتيب. مفيش ضمان إن الـ webhooks توصل بالترتيب. payment_failed من محاولة قديمة ممكن يوصل بعد succeeded.

طب الترتيب نحلّه إزاي؟ بـ state machine بتمشي لقدّام بس. الـ statuses ليها ترتيب: creating، وبعدين pending، وبعدين failed، وبعدين succeeded، وبعدين partially refunded، وبعدين refunded. أي event بيحاول يرجّع الـ payment لـ status أقدم، بيتجاهل. failed بعد succeeded؟ متجاهل. بس failed وبعدين succeeded؟ طبيعي، العميل الـ card الأولاني اترفض وجرّب card تاني. وفيه أسلوب تاني بتستخدمه Stripe كتير: الـ webhook يبقى مجرد تنبيه، وانت تعمل GET على الـ object من الـ provider وتاخد الـ status الحالي بتاعه. كده دايمًا معاك آخر حالة مهما كان الترتيب. وحاجة أخيرة: رد على الـ webhook بسرعة. سجّل الـ event، وغيّر الـ status، ورد بـ ميتين. والشغل التقيل، زي الشحن والإيميلات، ابعته لـ queue من الـ outbox. لو الشحن نفسه وقع، الـ provider مش هيعيد الـ webhook علشانه.

الـ refunds. ليها idempotency key برضه، مربوط بالـ ticket بتاع الـ refund، مش random. ومجموع الـ refunds ما يعدّيش المبلغ اللي اتدفع. والمشكلة إن اتنين admins ممكن يدوسوا في نفس الوقت، والاتنين يشوفوا إن فيه مبلغ متاح، والاتنين يرجّعوا. وده نفس الـ race اللي شفناه في درس الـ transactions. الحل: select for update على الـ payment، وبعدين نحسب المجموع، ونكتب الـ refund بـ pending، و commit. التاني بيستنى الأولاني يخلص، فيشوف الـ refund بتاعه في المجموع. وبعدين نكلّم الـ provider برّه الـ transaction، علشان ما نمسكش lock على الـ database وإحنا مستنيين الـ network. ولو الـ provider رفض، الـ refund يبقى failed، ويخرج من المجموع.

الـ reconciliation. حتى لو عملت كل ده صح، webhooks هتضيع: الـ server كان واقع ساعتين، أو الـ provider نفسه عنده مشكلة. فكل يوم، أو كل ساعة، فيه job بيجيب الـ payments من الـ provider ويقارنها باللي عندك: مدفوع عنده و pending عندك ← webhook ضاع، صلّحه بنفس الـ state machine. المبلغ أو الـ currency مختلفين ← ده مش حاجة تصلّحها أوتوماتيك، دي حاجة حد يبص عليها، alert. وكمان فيه الـ payouts: الفلوس اللي الـ provider حوّلها لحسابك فعلًا بعد الـ fees، ودي بتتقارن مع الـ payments والـ refunds. وفي الـ systems الكبيرة بيبقى فيه ledger بـ double entry، كل حركة فلوس ليها طرفين. وآخر حاجة: الـ disputes أو الـ chargebacks. العميل ممكن يكلّم البنك ويقول ما دفعتش، والـ provider يبعتلك webhook. ده status كمان في الـ state machine، ومعاه deadline ترد فيه بالأدلة.

التحدي. عندك psp dot js، payment provider شبه Stripe على HTTP: بيعمل intents و refunds بالـ idempotency keys، وبيعمل webhooks موقّعة، وتقدر تقوله يضيّع الـ response الجاي. و lab dot js بيمشي قصة كاملة، و test dot js. والمطلوب payments dot js. كل التفاصيل في الكومنت: migrate، و startCheckout، و verify، و apply بالـ state machine، و handleWebhook، و refund بالـ lock، و reconcile. اقرا الكومنت كويس، ونشغّل test dot js لحد ما تبقى أربعتاشر من أربعتاشر.

تمرين

اكتب payments.js: PaymentError، و migrate بتلات tables، و createPayments بـ startCheckout (unique على الـ order و idempotency key) و handleWebhook (signature و STALE و duplicate في نفس الـ transaction و state machine) و refund (for update والمجموع والـ key) و reconcile (fixed و mismatches). كل التفاصيل في الكومنت، وشغّل node test.js.

الحل. الـ checkout: insert on conflict do nothing، وبعدين select، فأي عدد requests للـ order يلاقوا نفس الـ row ونفس الـ key. الـ webhook: الـ verify برّه، وبعدين transaction فيها الـ event id والـ apply مع بعض. الـ apply: for update، وترتيب الـ statuses، والـ refunded بالأكبر. الـ refund: lock والمجموع والـ insert في transaction، والـ provider بعدها. والـ reconcile بيستخدم نفس الـ apply، فمفيش logic تاني ممكن يختلف. نشغّل lab dot js.

payments.js
// payments.js: checkout بالـ idempotency، و webhooks موقّعة ومن غير تكرار وبترتيب أي حاجة، و refunds ما تعدّيش المبلغ، و reconciliation
// lab.js و test.js بيعملوا import من هنا: PaymentError و migrate و createPayments
import { createHmac, timingSafeEqual } from "node:crypto";

export class PaymentError extends Error {
  constructor(code, extra = {}) { super(code); this.code = code; Object.assign(this, extra); }
}

export async function migrate(db) {
  await db.query(`
    create table if not exists payments (
      id serial primary key,
      order_id text not null unique,
      amount_cents int not null check (amount_cents > 0),
      currency text not null,
      status text not null,
      idempotency_key text not null unique,
      intent_id text unique,
      client_secret text,
      refunded_cents int not null default 0,
      updated_at timestamptz not null default now()
    );
    create table if not exists refunds (
      id serial primary key,
      payment_id int not null references payments(id),
      amount_cents int not null check (amount_cents > 0),
      idempotency_key text not null unique,
      status text not null,
      psp_refund_id text
    );
    create table if not exists webhook_events (
      event_id text primary key,
      type text not null,
      received_at timestamptz not null default now()
    );
  `);
}

const RANK = { creating: 0, pending: 1, failed: 2, succeeded: 3, partially_refunded: 4, refunded: 5 };

export function createPayments({ pool, psp, webhookSecret, toleranceMs = 300000, now = Date.now }) {
  async function call(path, body, key) {
    let res;
    try {
      res = await fetch(psp.baseUrl + path, {
        method: "POST",
        headers: { authorization: `Bearer ${psp.apiKey}`, "content-type": "application/json", "idempotency-key": key },
        body: JSON.stringify(body),
      });
    } catch {
      throw new PaymentError("PSP_UNAVAILABLE");
    }
    const out = await res.json();
    if (!res.ok) throw new PaymentError("PSP_REJECTED", { status: res.status, pspError: out.error });
    return out;
  }

  async function tx(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"); throw e; }
    finally { c.release(); }
  }

  async function startCheckout(orderId, amountCents, currency = "EGP") {
    if (!Number.isInteger(amountCents) || amountCents <= 0) throw new PaymentError("INVALID_AMOUNT");
    await pool.query(
      "insert into payments (order_id, amount_cents, currency, status, idempotency_key) values ($1, $2, $3, 'creating', $4) on conflict (order_id) do nothing",
      [orderId, amountCents, currency, `checkout:${orderId}`],
    );
    const { rows: [p] } = await pool.query("select * from payments where order_id = $1", [orderId]);
    if (p.amount_cents !== amountCents || p.currency !== currency) throw new PaymentError("AMOUNT_MISMATCH");
    if (!p.intent_id) 
…

المخرجات

$ node lab.js

--- 1) العميل داس Pay مرتين، والـ response الأولاني ضاع ---
  النتيجتين: ✘ PSP_UNAVAILABLE و pi_1
  الـ retry: pi_1. عدد الـ intents عند الـ provider: 1
  الـ requests للـ provider: checkout:ord-1 ، checkout:ord-1

--- 2) العميل دفع: الـ webhook وصل تلات مرات، وواحد قديم وصل بعدهم ---
  succeeded                ← {"status":"processed","paymentStatus":"succeeded"}
  succeeded (retry)        ← {"status":"duplicate"}
  succeeded (retry)        ← {"status":"duplicate"}
  payment_failed (اتأخر)   ← {"status":"ignored","reason":"STALE_TRANSITION","paymentStatus":"succeeded"}

--- 3) حد بيبعت webhooks من عنده ---
  من غير signature       ← ✘ BAD_SIGNATURE
  غيّر المبلغ في الـ body ← ✘ BAD_SIGNATURE
  event حقيقي من امبارح  ← ✘ STALE

--- 4) refunds ---
  تلاتين جنيه             ← {"refundId":1,"status":"succeeded","pspRefundId":"re_2","amountCents":3000}
  نفس الـ ticket تاني      ← {"refundId":1,"status":"succeeded","pspRefundId":"re_2","amountCents":3000}
  تلات admins في نفس الوقت، كل واحد أربعين ← ✔ 4000 ، ✔ 4000 ، ✘ AMOUNT_TOO_LARGE
  webhook الـ refund       ← {"status":"processed","paymentStatus":"partially_refunded"}
  عند الـ provider: اترجع 11000 من 11410

--- 5) 
…

الأول: الضغطتين راحوا بنفس الـ key، واحدة الـ response بتاعها ضاع، والـ retry رجّع نفس الـ intent. intent واحد بس عند الـ provider. التاني: succeeded اتعمل مرة، والتكرار duplicate، و payment_failed اللي اتأخر اتجاهل. التالت: المزوّر، والمتعدّل، والقديم، كلهم اترفضوا. الرابع: نفس الـ ticket رجّع نفس الـ refund. وتلات admins مع بعض، اتنين بس نجحوا، لأن التالت كان هيعدّي المبلغ. والخامس: webhook ضاع، والـ reconcile لقاه وصلّحه. ونشغّل test dot js.

payments.js

المخرجات

$ node test.js
✅ migrate تتعمل مرتين من غير مشاكل، والـ tables موجودة 
✅ startCheckout: payment intent عند الـ provider، والـ row بـ pending، والـ key مربوط بالـ order {"c1":{"paymentId":1,"intentId":"pi_1","clientSecret":"pi_1_secret_1","status":"pending"},"key":"checkout:o1"}
✅ نفس الـ order تاني ← نفس الـ intent، ومن غير ما نكلّم الـ provider 
✅ الـ response ضاع ← PSP_UNAVAILABLE، والـ retry بنفس الـ key ← نفس الـ intent، مش اتنين {"e4":"PSP_UNAVAILABLE","mid4":{"status":"creating","refunded_cents":0},"c2":{"paymentId":3,"intentId":"pi_2","clientSecret":"pi_2_secret_2","status":"pending"}}
✅ خمس clicks في نفس الوقت ← intent واحد 
✅ INVALID_AMOUNT و AMOUNT_MISMATCH 
✅ webhook: body متعدّل أو signature غلط أو مفيش ← BAD_SIGNATURE، وقديم ← STALE، ومحصلش أي تغيير ["BAD_SIGNATURE","BAD_SIGNATURE","BAD_SIGNATURE","STALE"]
✅ webhook succeeded ← succeeded، ونفس الـ event تاني ← duplicate {"w8":{"status":"processed","paymentStatus":"succeeded"},"d8":{"status":"duplicate"}}
✅ الترتيب: failed بعد succeeded ← ignored، و failed وبعدين succeeded ← succeeded {"w9a":{"status":"ignored","reason":"STALE_TRANSITION","paymentStatus":"succeeded"},"w9b":{"status":"processed","paymentStatus":"failed"}
…

كله نجح. الـ amounts والـ currencies فتحت موضوع أكبر: الـ users في بلاد مختلفة. الدرس الجاي: الـ internationalization والـ timezones. ليه تخزّن UTC، وإزاي تحسب نص الليل عند user في القاهرة وواحد في طوكيو، والـ daylight saving، والترجمات، والأرقام والتواريخ بلغة كل user.

checkout.naive.js
// checkout.naive.js: الدفع زي ما كان مكتوب
app.post("/checkout", async (req, res) => {
  const order = await db.orders.find(req.body.orderId);
  const pi = await fetch(`${PSP}/v1/payment_intents`, {
    method: "POST",
    headers: { authorization: `Bearer ${KEY}` },
    body: JSON.stringify({ amount: order.total * 100, currency: "EGP" }), // total = 114.1
  }).then((r) => r.json());
  await db.payments.insert({ orderId: order.id, intentId: pi.id });
  res.json({ clientSecret: pi.client_secret });
});

// الـ provider بيرجّع العميل هنا بعد الدفع
app.get("/checkout/return", async (req, res) => {
  if (req.query.status === "success") await db.orders.update(req.query.orderId, { status: "paid" });
  res.redirect("/thanks");
});

app.post("/webhooks/psp", express.json(), async (req, res) => {
  const event = req.body;
  if (event.type === "payment_intent.succeeded") await db.payments.update(event.data.object.id, { status: "succeeded" });
  if (event.type === "payment_intent.payment_failed") await db.payments.update(event.data.object.id, { status: "failed" });
  await shipOrder(event.data.object.metadata.orderId);
  res.sendStatus(200);
});

app.post("/admin/refund", async (req, res) => {
  await fetch(`${PSP}/v1/refunds`, { method: "POST", headers: { authorization: `Bearer ${KEY}` }, body: JSON.stringify({ payment_intent: req.body.intentId, amount: req.body.amount }) });
  res.sendStatus(200);
});
psp.js
// psp.js: payment provider مزيّف شبه Stripe على HTTP (ما تغيّروش). idempotency keys، و webhooks موقّعة، و responses بتضيع
import http from "node:http";
import { createHmac } from "node:crypto";

export async function startPsp({ apiKey, webhookSecret }) {
  const state = { intents: new Map(), refunds: new Map(), keys: new Map(), requests: [], dropNextResponse: false };
  let n = 0, ev = 0;

  function sign(type, object, { created = Math.floor(Date.now() / 1000), id = `evt_${++ev}` } = {}) {
    const raw = JSON.stringify({ id, type, created, data: { object } });
    const t = created;
    const v1 = createHmac("sha256", webhookSecret).update(`${t}.${raw}`).digest("hex");
    return { raw, header: `t=${t},v1=${v1}`, id };
  }

  function createIntent(body) {
    const id = `pi_${++n}`;
    const pi = { id, amount: body.amount, currency: body.currency, metadata: body.metadata ?? {}, status: "requires_payment_method", amount_refunded: 0, client_secret: `${id}_secret_${n}` };
    state.intents.set(id, pi);
    return [200, pi];
  }

  function createRefund(body) {
    const pi = state.intents.get(body.payment_intent);
    if (!pi) return [404, { error: "no_such_payment_intent" }];
    if (pi.status !== "succeeded") return [400, { error: "charge_not_captured" }];
    if (!Number.isInteger(body.amount) || body.amount <= 0 || body.amount > pi.amount - pi.amount_refunded) return [400, { error: "amount_too_large" }];
    pi.amount_refunded += body.amount;
    const re = { id: `re_${++n}`, payment_intent: pi.id, amount: body.amount, status: "succeeded" };
    state.refunds.set(re.id, re);
    return [200, re];
  }

  const server = http.createServer(async (req, res) => {
    let raw = "";
    for await (const c of req) raw += c;
    const body = raw ? JSON.parse(raw) : {};
    const key = req.headers["idempotency-key"] ?? null;
    state.requests.push({ method: req.method, path: req.url, key, body });
    const send = (status, obj, replayed = false) => {
      if (state.dropNextResponse && req.method === "POST") { state.dropNextResponse = false; return req.socket.destroy(); }
      res.writeHead(status, { "content-type": "application/json", ...(replayed ? { "idempotent-replayed": "true" } : {}) });
      res.end(JSON.stringify(obj));
    };
    if (req.headers.authorization !== `Bearer ${apiKey}`) return send(401, { error: "unauthorized" });
    if (req.method === "GET" && req.url.startsWith("/v1/payment_intents")) return send(200, { data: [...state.intents.values()] });
    if (req.method !== "POST") return send(404, { error: "not_found" });
    if (!key) return send(400, { error: "idempotency_key_required" });
    const scoped = `${req.url}:${key}`;
    const prev = state.keys.get(scoped);
    if (prev) return prev.raw === raw ? send(prev.status, prev.body, true) : send(400, { error: "idempotency_key_reused" });
    let out;
    if (req.url === "/v1/payment_intents") out = createIntent(body);
    else if (req.url === "/v1/refunds") out = createRefund(bod
…
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