Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
الـ ACLs: user لكل service بـ keys محددة (~cache:*) وأوامر محددة (+@read و -@dangerous)، و NOPERM و WRONGPASS، و least privilege. Redis Cluster بتجربة حقيقية: 3 masters و 16384 slot، و KEYSLOT، و CROSSSLOT، والـ hash tags {user:7}. والمراقبة: hit ratio من INFO stats، و used_memory، و SLOWLOG، و MEMORY USAGE للـ big keys، و CLIENT LIST.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. Redis من غير password شغال على أي جهاز عليه، وأي حد يوصله يقدر يعمل FLUSHALL ويمسح كل حاجة. وفي الإنتاج اتسرقت شركات من Redis مفتوح على الإنترنت. أول خط دفاع: Redis ما يبقاش مكشوف خالص، في private network. التاني: ACLs. ACL SETUSER: user اسمه app، بـ password. الـ tilde cache star: يقدر يلمس الـ keys اللي بتبدأ بـ cache بس. plus at read و plus at write: أوامر القراية والكتابة. و minus at dangerous: من غير FLUSHALL و KEYS و CONFIG واللي زيهم. نشغّل.
import Redis from "ioredis";
const admin = new Redis(process.env.REDIS_URL);
await admin.flushall();
// user للـ app: keys بتبدأ بـ cache: بس، ومن غير أوامر خطيرة
await admin.acl("SETUSER", "app", "reset", "on", ">app-secret", "~cache:*", "+@read", "+@write", "-@dangerous");
// enableReadyCheck: false لأن ioredis بيسأل INFO أول ما يتصل، والـ user ده مالوش INFO
const app = new Redis({ host: "localhost", port: 6379, username: "app", password: "app-secret", enableReadyCheck: false });
const tryIt = async (label, fn) => {
try {
console.log(label.padEnd(28), "→", await fn());
} catch (err) {
console.log(label.padEnd(28), "→", err.message.split(":")[0]);
}
};
await tryIt("SET cache:home", () => app.set("cache:home", "html"));
await tryIt("GET cache:home", () => app.get("cache:home"));
await tryIt("SET sess:7 (key مش مسموح)", () => app.set("sess:7", "x"));
await tryIt("FLUSHALL", () => app.flushall());
await tryIt("KEYS *", () => app.keys("*"));
await tryIt("CONFIG GET", () => app.config("GET", "maxmemory"));
const probe = new Redis(process.env.REDIS_URL);
await tryIt("AUTH app بـ password غلط", () => probe.call("AUTH", "app", "wrong"));
for (const c of [admin, app, probe]) c.disconnect();المخرجات
$ node main.js SET cache:home → OK GET cache:home → html SET sess:7 (key مش مسموح) → NOPERM this user has no permissions to access one of the keys used as arguments FLUSHALL → NOPERM this user has no permissions to run the 'flushall' command or its subcommand KEYS * → NOPERM this user has no permissions to run the 'keys' command or its subcommand CONFIG GET → NOPERM this user has no permissions to run the 'config' command or its subcommand AUTH app بـ password غلط → WRONGPASS invalid username-password pair or user is disabled.
SET و GET على cache: OK. على sess: NOPERM، الـ key برة النطاق. FLUSHALL و KEYS و CONFIG: NOPERM. و AUTH بـ password غلط: WRONGPASS. القاعدة اسمها least privilege: كل service ياخد أقل حاجة يحتاجها، فلو اتخترق، الضرر محدود. Redis Cluster: لما البيانات أكبر من memory جهاز واحد، أو الـ traffic أكبر من thread واحد. الـ cluster بيقسم الـ keys على كام master. كل key بيتحوّل لرقم من ستاشر ألف تلتمية أربعة وتمانين slot، وكل master شايل مجموعة slots. cluster dot sh بيشغّل تلات masters، و redis-cli dash dash cluster create بيوزّع الـ slots عليهم. و main dot js بيستخدم Redis dot Cluster من ioredis: بيعرف أنهي key عند أنهي master لوحده. نشغّل الـ cluster والـ demo.
import Redis from "ioredis";
const cluster = new Redis.Cluster([{ host: "127.0.0.1", port: 7001 }]);
// كل key بيتحوّل لرقم slot من 16384، وكل master شايل جزء من الـ slots
for (const k of ["user:7", "user:8", "cart:7"]) {
console.log(k, "← slot", await cluster.cluster("KEYSLOT", k));
}
// أمر على أكتر من key لازم يكونوا في نفس الـ slot
try {
await cluster.mget("user:7", "cart:7");
} catch (err) {
console.log("MGET على slots مختلفة:", err.message.split(":")[0]);
}
// hash tag: الجزء اللي بين {} هو اللي بيتحسب منه الـ slot
console.log("{user:7}:profile ← slot", await cluster.cluster("KEYSLOT", "{user:7}:profile"));
console.log("{user:7}:cart ← slot", await cluster.cluster("KEYSLOT", "{user:7}:cart"));
await cluster.mset("{user:7}:profile", "mona", "{user:7}:cart", "3 items");
console.log("MGET بالـ hash tag:", await cluster.mget("{user:7}:profile", "{user:7}:cart"));
cluster.disconnect();المخرجات
$ bash cluster.sh && node main.js; bash cluster.sh down
127.0.0.1:7001 ← 0 keys | 5461 slots | 0 slaves.
127.0.0.1:7003 ← 0 keys | 5461 slots | 0 slaves.
127.0.0.1:7002 ← 0 keys | 5462 slots | 0 slaves.
user:7 ← slot 2780
user:8 ← slot 15155
cart:7 ← slot 9546
MGET على slots مختلفة: CROSSSLOT Keys in request don't hash to the same slot
{user:7}:profile ← slot 2780
{user:7}:cart ← slot 2780
MGET بالـ hash tag: [ 'mona', '3 items' ]الـ slots اتقسمت تلات حتت، حوالي خمس آلاف وخمسمية لكل master. user سبعة و user تمانية و cart سبعة: كل واحد في slot مختلف. MGET على user سبعة و cart سبعة: CROSSSLOT، لأن الـ keys على masters مختلفة، والأمر لازم يشتغل على master واحد. والحل: hash tag. الجزء اللي بين curly braces هو اللي بيتحسب منه الـ slot، فـ curly user سبعة profile و curly user سبعة cart في نفس الـ slot، و MGET اشتغل. ونفس القاعدة للـ Lua scripts و MULTI: كل الـ keys في نفس الـ slot. المراقبة. hit ratio: من INFO stats، الـ hits على الـ hits زايد الـ misses. لو قليل، الـ cache مش بيعمل شغله. used_memory. SLOWLOG: أي أمر أبطأ من حد معين بيتسجل، وهنا عملنا LRANGE على list فيها مِيتين ألف حاجة. MEMORY USAGE للـ big keys. و CLIENT LIST: عدد الـ connections.
نشغّل.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
await redis.flushall();
await redis.config("SET", "slowlog-log-slower-than", "1000"); // أي أمر أبطأ من 1ms
// شوية traffic: hits و misses وأمر بطيء
for (let i = 0; i < 50; i++) await redis.set(`cache:${i}`, "x".repeat(100));
for (let i = 0; i < 80; i++) await redis.get(`cache:${i}`); // 50 hit و 30 miss
for (let b = 0; b < 20; b++) {
await redis.rpush("big:list", ...Array.from({ length: 10000 }, (_, i) => String(b * 10000 + i)));
}
await redis.lrange("big:list", 0, -1); // أمر بطيء: بيرجّع 200 ألف حاجة
const info = await redis.info("stats");
const stat = (name) => Number(info.match(new RegExp(`${name}:(\\d+)`))[1]);
const hits = stat("keyspace_hits");
const misses = stat("keyspace_misses");
console.log("hit ratio:", Math.round((100 * hits) / (hits + misses)) + "%");
const mem = await redis.info("memory");
console.log("used_memory > 1MB:", Number(mem.match(/used_memory:(\d+)/)[1]) > 1024 * 1024);
const slow = await redis.slowlog("GET", 5);
console.log("slowlog:", slow.map((e) => e[3].slice(0, 2).join(" ")));
// أكبر key (زي redis-cli --bigkeys بس لـ key واحد)
console.log("big:list:", Math.round((await redis.memory("USAGE", "big:list", "SAMPLES", "0")) / 1024), "KB");
console.log("clients:", (await redis.client("LIST")).trim().split("\n").length);
redis.disconnect();المخرجات
$ node main.js hit ratio: 63% used_memory > 1MB: true slowlog: [ 'lrange big:list', 'rpush big:list', 'rpush big:list', 'rpush big:list' ] big:list: 950 KB clients: 1
hit ratio أكتر من ستين في المِيّة: خمسين hit و تلاتين miss، وشوية hits تانية. الـ memory. الـ slowlog فيه الـ RPUSH والـ LRANGE الكبار. والـ big list حجمها بالـ KB، وبـ SAMPLES zero علشان يحسبها كلها مش عينة. وخد بالك: Redis thread واحد، فأمر واحد بطيء زي LRANGE على list ضخمة بيوقّف كل الـ clients التانيين وهو شغال. علشان كده الـ big keys والـ slowlog أهم حاجتين تراقبهم. التحدي: least privilege لكل service. تلات users: api: الـ cache والـ sessions، قراية وكتابة. worker: الـ queues بس، وأوامر الـ lists بس. metrics: INFO و SLOWLOG بس، ومن غير أي key. وتأكّد بالتجربة إن كل حاجة زيادة مرفوضة. التفاصيل في الكومنت.
3 users بـ ACL SETUSER reset: api (~cache:* ~sess:* +@read +@write -@dangerous)، و worker (~queue:* +@list +ping)، و metrics (+info +slowlog +ping)، وجرّب المسموح والممنوع.
الحل. تلات SETUSER، كل واحد بيبدأ بـ reset، علشان يبدأ من غير أي صلاحية. وتجارب لكل واحد. و CLIENT LIST من الـ admin. نشغّل.
import Redis from "ioredis";
const admin = new Redis(process.env.REDIS_URL);
await admin.flushall();
const as = (username, password) => new Redis({ host: "localhost", port: 6379, username, password, enableReadyCheck: false });
const tryIt = async (label, fn) => {
try { console.log(label.padEnd(32), "→ ok", await fn()); }
catch (err) { console.log(label.padEnd(32), "→", err.message.split(":")[0]); }
};
await admin.acl("SETUSER", "api", "reset", "on", ">api-pass", "~cache:*", "~sess:*", "+@read", "+@write", "-@dangerous");
await admin.acl("SETUSER", "worker", "reset", "on", ">worker-pass", "~queue:*", "+@list", "+ping");
await admin.acl("SETUSER", "metrics", "reset", "on", ">metrics-pass", "+info", "+slowlog", "+ping");
const api = as("api", "api-pass");
const worker = as("worker", "worker-pass");
const metrics = as("metrics", "metrics-pass");
await tryIt("api SET sess:7", () => api.set("sess:7", "data"));
await tryIt("api GET queue:jobs", () => api.get("queue:jobs"));
await tryIt("api FLUSHDB", () => api.flushdb());
await tryIt("worker LPUSH queue:jobs", () => worker.lpush("queue:jobs", "job1"));
await tryIt("worker SET queue:x", () => worker.set("queue:x", "1"));
await tryIt("worker LPUSH cache:a", () => worker.lpush("cache:a", "1"));
await tryIt("metrics INFO", async () => (await metrics.info("server")).includes("redis_version"));
await tryIt("metrics GET cache:a", () => metrics.get("cache:a"));
// الـ admin شايف كل connection والـ user بتاعها
const users = (await admin.client("LIST")).match(/user=\w+/g);
console.log("connections:", [...new Set(users)].sort().join(" "));
for (const c of [admin, api, worker, metrics]) c.disconnect();المخرجات
$ node main.js api SET sess:7 → ok OK api GET queue:jobs → NOPERM this user has no permissions to access one of the keys used as arguments api FLUSHDB → NOPERM this user has no permissions to run the 'flushdb' command or its subcommand worker LPUSH queue:jobs → ok 1 worker SET queue:x → NOPERM this user has no permissions to run the 'set' command or its subcommand worker LPUSH cache:a → NOPERM this user has no permissions to access one of the keys used as arguments metrics INFO → ok true metrics GET cache:a → NOPERM this user has no permissions to run the 'get' command or its subcommand connections: user=api user=default user=metrics user=worker
كل المسموح ok، وكل الممنوع NOPERM، و CLIENT LIST شايف كل connection باسم الـ user بتاعها. كده خلصنا Redis. القسم الجاي: الـ authentication والـ authorization: الـ passwords، والـ sessions، والـ CSRF والـ XSS، و OAuth، و JWT، والـ passkeys.
#!/bin/bash
# 3 masters على 7001..7003 (في الإنتاج: كل master معاه replica)
if [ "$1" = "down" ]; then
for p in 7001 7002 7003; do redis-cli -p $p SHUTDOWN NOSAVE > /dev/null 2>&1 || true; done
exit 0
fi
rm -rf cluster && mkdir cluster
for p in 7001 7002 7003; do
redis-server --port $p --cluster-enabled yes --cluster-config-file nodes-$p.conf \
--dir cluster --save "" --appendonly no --daemonize yes --logfile "$PWD/cluster/$p.log"
done
sleep 0.5
redis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 --cluster-yes > cluster/create.log
until redis-cli -p 7001 CLUSTER INFO | grep -q 'cluster_state:ok'; do sleep 0.1; done
redis-cli --cluster check 127.0.0.1:7001 | grep -E '^127' | sed 's/ (.*) -> / ← /'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