Redis Streams والـ Consumer Groups: log بيتوزع على workers
الـ stream: log append-only بـ XADD و ids بالوقت، و XRANGE، و MAXLEN ~ للحجم. الـ consumer groups: XREADGROUP بيوزّع على الـ consumers، و XACK بعد المعالجة، والـ pending entries list بـ XPENDING (مين ماسك إيه وكام مرة اتسلّم). worker مات؟ XAUTOCLAIM بيستلم المعلّق. والـ dead-letter stream للي بيفشل على طول، وإن التسليم at-least-once.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. الـ list في Redis ممكن تبقى queue بسيطة، بس لو worker سحب حاجة ومات، ضاعت. Redis Streams معمولة للمشكلة دي بالزبط. الـ stream: log، بيتزوّد في آخره بس، وكل entry ليه id فيه الوقت بالـ milliseconds ورقم. XADD بيضيف، والـ star معناها: اعمل id لوحدك. XRANGE بيقرا من أول لآخر. و MAXLEN مع tilde: خلي الطول حوالي ألف، علشان الـ memory ما تخلصش. نشغّل.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
await redis.flushall();
// stream: log بيتزوّد في آخره بس، وكل entry ليه id بالوقت
const id1 = await redis.xadd("orders", "*", "orderId", "7", "total", "250");
const id2 = await redis.xadd("orders", "*", "orderId", "8", "total", "90");
console.log("ids:", id1, id2, "← <millisecond>-<رقم>");
const all = await redis.xrange("orders", "-", "+");
console.log(all.map(([, fields]) => fields));
// MAXLEN ~: خلي الـ stream في حدود معينة (الأقدم بيتشال)
for (let i = 0; i < 2000; i++) await redis.xadd("orders", "MAXLEN", "~", "1000", "*", "orderId", String(100 + i));
console.log("الطول:", (await redis.xlen("orders")) <= 1100 ? "حوالي 1000" : "كبير");
redis.disconnect();المخرجات
$ node main.js ids: 1792245377486-0 1792245377486-1 ← <millisecond>-<رقم> [ [ 'orderId', '7', 'total', '250' ], [ 'orderId', '8', 'total', '90' ] ] الطول: حوالي 1000
الـ ids: الوقت بالـ milliseconds، وبعده dash ورقم، والرقم بيزيد بس لو اتنين اتضافوا في نفس الـ millisecond. الـ entries بالحقول. والطول بعد ألفين إضافة: حوالي ألف. والـ tilde معناها مش لازم بالزبط، فـ Redis بيقص بكفاءة. الـ consumer groups: أهم حاجة في الـ streams. group اسمها billing، وفيها workers. XREADGROUP بالـ greater than: هات entries جديدة محدش في الـ group استلمها، و Redis بيوزّع: كل entry لـ worker واحد. بعد ما الـ worker يخلص، XACK: خلّصت. اللي اتسلّم ومالوش ACK بيفضل في قايمة اسمها pending. و XAUTOCLAIM: worker تالت بيستلم أي حاجة معلّقة بقالها أكتر من وقت معين، يعني صاحبها غالبًا مات. نشغّل.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
await redis.flushall();
for (let i = 1; i <= 6; i++) await redis.xadd("orders", "*", "orderId", String(i));
// consumer group: الـ entries بتتوزع على الـ consumers، وكل واحد بيعمل ACK بعد ما يخلص
await redis.xgroup("CREATE", "orders", "billing", "0");
async function consume(name, count) {
const res = await redis.xreadgroup("GROUP", "billing", name, "COUNT", count, "STREAMS", "orders", ">");
return res ? res[0][1] : [];
}
const a = await consume("worker-a", 2);
const b = await consume("worker-b", 2);
console.log("a أخد:", a.map(([, f]) => f[1]), "| b أخد:", b.map(([, f]) => f[1]));
// a خلّص وعمل ACK، و b مات من غير ACK
await redis.xack("orders", "billing", ...a.map(([id]) => id));
const pending = await redis.xpending("orders", "billing", "-", "+", 10);
console.log("pending:", pending.map(([id, consumer, idle, deliveries]) => `${consumer} (${deliveries})`));
// worker-c بيستلم اللي بقاله أكتر من 100ms مستني من غير ACK
await new Promise((r) => setTimeout(r, 150));
const [, claimed] = await redis.xautoclaim("orders", "billing", "worker-c", 100, "0", "COUNT", 10);
console.log("c استلم من b:", claimed.map(([, f]) => f[1]));
console.log("c الجديد:", (await consume("worker-c", 10)).map(([, f]) => f[1]));
redis.disconnect();المخرجات
$ node main.js a أخد: [ '1', '2' ] | b أخد: [ '3', '4' ] pending: [ 'worker-b (1)', 'worker-b (1)' ] c استلم من b: [ '3', '4' ] c الجديد: [ '5', '6' ]
worker a أخد واحد واتنين، و b أخد تلاتة وأربعة، من غير تكرار. a عمل ACK، و b مات. الـ pending: الاتنين بتوع worker b، وكل واحد اتسلّم مرة. worker c استلمهم بالـ autoclaim. وبعدين أخد الجديد: خمسة وستة. يعني ولا order ضاع. بس خد بالك: تلاتة وأربعة ممكن يكونوا اتعالجوا جزئيًا عند b قبل ما يموت، فهيتعالجوا مرة تانية. ده at-least-once، والـ handler لازم يبقى idempotent. الـ Streams مقابل Pub Sub مقابل Kafka. Pub Sub: الرسالة بتتبعت للي سامع دلوقتي بس، ولو مفيش حد، ضاعت. Streams: الرسايل محفوظة، والـ consumer يقرا من أي مكان، و groups و ACKs. Kafka: نفس الفكرة بس على disk وبحجم ضخم و retention طويل. وليه درس قدام. التحدي: worker بيستلم وبيعيد وبيدفن. loop بتستلم المعلّق بالـ autoclaim، وبعدين الجديد. نجح: ACK. فشل: تشوف اتسلّم كام مرة، ولو تلاتة، تنقله لـ stream اسمه orders dead، وتعمل ACK. والـ loop تخلص لما مفيش مهام. و order خمسة بايز وبيقع كل مرة. التفاصيل في الكومنت.
loop(name): XAUTOCLAIM (50ms) + XREADGROUP، نجاح ← XACK، فشل ← deliveries من XPENDING، ولو >= 3 ← XADD orders:dead و XACK. اتنين workers.
الحل. كل لفة: autoclaim، وبعدين readgroup. لكل entry: handle، و ACK. في الـ catch: XPENDING للـ id ده بيرجّع عدد مرات التسليم، ولو تلاتة: XADD للـ dead، و ACK. وفي آخر اللفة: لو مفيش جديد ولا مستلم، و pending بـ zero، نخرج. نشغّل.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
await redis.flushall();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 1; i <= 8; i++) await redis.xadd("orders", "*", "orderId", String(i));
await redis.xgroup("CREATE", "orders", "billing", "0");
// order رقم 5 بايز: الـ handler بيقع عليه كل مرة
const processed = [];
async function handle(fields) {
if (fields[1] === "5") throw new Error("payment provider رفض");
processed.push(fields[1]);
}
async function loop(name) {
for (;;) {
const [, claimed] = await redis.xautoclaim("orders", "billing", name, 50, "0", "COUNT", 10);
const res = await redis.xreadgroup("GROUP", "billing", name, "COUNT", 5, "STREAMS", "orders", ">");
const fresh = res ? res[0][1] : [];
for (const [id, fields] of [...claimed, ...fresh]) {
try {
await handle(fields);
await redis.xack("orders", "billing", id);
} catch (err) {
const [[, , , deliveries]] = await redis.xpending("orders", "billing", id, id, 1);
if (deliveries >= 3) {
await redis.xadd("orders:dead", "*", ...fields, "error", err.message);
await redis.xack("orders", "billing", id);
}
}
}
const [count] = await redis.xpending("orders", "billing");
if (!fresh.length && !claimed.length && count === 0) return;
await sleep(60);
}
}
await Promise.all([loop("worker-a"), loop("worker-b")]);
console.log("processed:", processed.sort((x, y) => x - y));
console.log("dead:", (await redis.xrange("orders:dead", "-", "+")).map(([, f]) => f));
redis.disconnect();المخرجات
$ node main.js processed: [ '1', '2', '3', '4', '6', '7', '8' ] dead: [ [ 'orderId', '5', 'error', 'payment provider رفض' ] ]
السبعة السليمين اتعالجوا مرة واحدة، وخمسة في الـ dead ومعاه السبب. الدرس الجاي: Pub Sub و BullMQ.
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