Partial و Covering indexes: indexes أصغر وأسرع
الـ partial index بـ WHERE: بيغطي الصفوف اللي بتتسأل بس (زي الـ pending)، فحجمه صغير. الـ unique partial index للـ soft delete ولمنع التكرار طول ما الحاجة شغالة. الـ covering index بـ INCLUDE والـ Index Only Scan، ودور VACUUM والـ visibility map في الـ Heap Fetches.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. في الـ orders، عشرة في المِيّة بس pending، والـ dashboard طول الوقت بيسأل: هات أقدم pending. لو عملت index عادي على status و created_at، هو بيغطي المِيتين ألف صف كلهم، مع إن السؤال عن عشرين ألف بس. الـ partial index: index بـ WHERE، بيحط فيه الصفوف اللي بتطابق الشرط بس. هنعمل الاتنين ونقارن الحجم، ونشوف مين بيتستخدم. نشغّل.
-- 10% بس pending، والـ dashboard بيسأل عليهم بس
CREATE INDEX orders_status_full ON orders (status, created_at);
CREATE INDEX orders_pending ON orders (created_at) WHERE status = 'pending';
SELECT indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes WHERE relname = 'orders' AND indexrelname <> 'orders_pkey';
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE status = 'pending' ORDER BY created_at LIMIT 10;
-- الـ partial ما ينفعش لسؤال تاني
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE status = 'paid' ORDER BY created_at LIMIT 10;المخرجات
$ psql -q -f seed.sql -f queries.sql
index | size
--------------------+---------
orders_status_full | 6184 kB
orders_pending | 416 kB
(2 rows)
QUERY PLAN
-------------------------------------------------
Limit
-> Index Scan using orders_pending on orders
(2 rows)
QUERY PLAN
-----------------------------------------------------
Limit
-> Index Scan using orders_status_full on orders
Index Cond: (status = 'paid'::text)
(3 rows)الـ index الكامل حوالي ستة ميجا، والـ partial حوالي أربعمية كيلو، يعني أصغر حوالي خمستاشر مرة. وسؤال الـ pending استخدم الـ partial. بس سؤال الـ paid ما ينفعش يستخدمه، لأن الـ paid مش فيه أصلًا. الـ index الأصغر يعني: memory أقل، والـ inserts للـ paid ما بتلمسوش خالص، والـ cache بيشيله كله. الـ partial ممكن يبقى unique كمان، ودي حيلة مهمة جدًّا. الـ soft delete: بدل ما تمسح الحساب، بتحط deleted_at. بس لو الإيميل unique عادي، المستخدم مش هيعرف يعمل حساب جديد بنفس الإيميل بعد ما مسح القديم. الحل: unique على lower email، بشرط deleted_at IS NULL. نشغّل.
-- unique بشرط: إيميل واحد بين الحسابات اللي ما اتمسحتش بس (soft delete)
DROP TABLE IF EXISTS accounts;
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
deleted_at timestamptz
);
CREATE UNIQUE INDEX accounts_email_live ON accounts (lower(email)) WHERE deleted_at IS NULL;
INSERT INTO accounts (email) VALUES ('[email protected]');
INSERT INTO accounts (email) VALUES ('[email protected]'); -- مرفوض
UPDATE accounts SET deleted_at = now() WHERE email = '[email protected]';
INSERT INTO accounts (email) VALUES ('[email protected]'); -- مسموح بعد الحذف
SELECT id, email, deleted_at IS NOT NULL AS deleted FROM accounts ORDER BY id;المخرجات
$ psql -q -f seed.sql -f queries.sql psql:queries.sql:11: ERROR: duplicate key value violates unique constraint "accounts_email_live" DETAIL: Key (lower(email))=([email protected]) already exists. id | email | deleted ----+------------+--------- 1 | [email protected] | t 3 | [email protected] | f (2 rows)
MONA الكبيرة اترفضت، لأن فيه حساب عايش بنفس الإيميل. بعد المسح، نفس الإيميل اتقبل. والجدول فيه الاتنين: القديم ممسوح، والجديد عايش. ونفس الفكرة تنفع لحاجات كتير: اشتراك واحد active لكل مستخدم، أو job واحدة شغالة بنفس الاسم. الـ covering index. عادةً الـ index بيقول الصف فين، و Postgres بيروح يجيب الصف نفسه من الجدول، ودي اسمها heap fetch. لو الـ index فيه كل الأعمدة اللي الـ query محتاجاها، يقدر يرد من الـ index لوحده: Index Only Scan. و INCLUDE بيضيف أعمدة للـ index، مش للترتيب، بس علشان تتقري منه. و VACUUM مهم هنا، هنفهم ليه. نشغّل.
-- covering index: الـ index نفسه فيه كل اللي الـ query محتاجاه
CREATE INDEX orders_user ON orders (user_id);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT user_id, sum(total_cents) FROM orders WHERE user_id BETWEEN 100 AND 110 GROUP BY user_id;
CREATE INDEX orders_user_cover ON orders (user_id) INCLUDE (total_cents);
VACUUM orders; -- بيحدّث الـ visibility map
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT user_id, sum(total_cents) FROM orders WHERE user_id BETWEEN 100 AND 110 GROUP BY user_id;المخرجات
$ psql -q -f seed.sql -f queries.sql
QUERY PLAN
------------------------------------------------------------------------
HashAggregate (actual rows=11 loops=1)
Group Key: user_id
Batches: 1 Memory Usage: 37kB
-> Bitmap Heap Scan on orders (actual rows=440 loops=1)
Recheck Cond: ((user_id >= 100) AND (user_id <= 110))
Heap Blocks: exact=40
-> Bitmap Index Scan on orders_user (actual rows=440 loops=1)
Index Cond: ((user_id >= 100) AND (user_id <= 110))
(8 rows)
QUERY PLAN
-----------------------------------------------------------------------------------
GroupAggregate (actual rows=11 loops=1)
Group Key: user_id
-> Index Only Scan using orders_user_cover on orders (actual rows=440 loops=1)
Index Cond: ((user_id >= 100) AND (user_id <= 110))
Heap Fetches: 0
(5 rows)الأولى: Bitmap Heap Scan، يعني راح للجدول يجيب الـ total_cents. التانية: Index Only Scan، و Heap Fetches zero. الـ Heap Fetches دي مهمة: Postgres لازم يتأكد إن الصف ده مرئي للـ transaction بتاعتك، وبيعرف ده من حاجة اسمها visibility map، و VACUUM هو اللي بيعدّلها. من غير VACUUM، الـ Index Only Scan كان هيروح للجدول برضه. وهنفهم السبب في درس الـ MVCC. التحدي: indexes لطابور الشغل. جدول jobs فيه مِيّة ألف، وكلهم خلصوا ما عدا مِيتين. والـ workers بيسألوا كل تانية عن اللي لسه. partial index على الـ queue والـ run_at للي لسه ما خلصوش. و unique partial على dedupe_key، علشان نفس الـ job ما تتكررش طول ما هي لسه. التفاصيل في الكومنت.
jobs_pending على (queue, run_at) WHERE done_at IS NULL، و jobs_dedupe unique على dedupe_key WHERE done_at IS NULL، وجرّب الـ EXPLAIN والتكرار والحجم.
الحل. الاتنين بـ WHERE done_at IS NULL. والـ EXPLAIN بنفس الشرط بالزبط، وإلا Postgres مش هيعرف إن الـ index ينفع. نشغّل.
DROP TABLE IF EXISTS jobs;
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
queue text NOT NULL,
payload jsonb NOT NULL,
run_at timestamptz NOT NULL,
done_at timestamptz,
dedupe_key text
);
-- 100 ألف job، كلهم خلصوا ما عدا 200
INSERT INTO jobs (queue, payload, run_at, done_at)
SELECT CASE WHEN i % 2 = 0 THEN 'email' ELSE 'video' END, '{}',
timestamptz '2026-01-01' + i * interval '1 minute',
CASE WHEN i > 99800 THEN NULL ELSE timestamptz '2026-01-01' + i * interval '1 minute' END
FROM generate_series(1, 100000) AS i;
CREATE INDEX jobs_pending ON jobs (queue, run_at) WHERE done_at IS NULL;
CREATE UNIQUE INDEX jobs_dedupe ON jobs (dedupe_key) WHERE done_at IS NULL;
ANALYZE jobs;
EXPLAIN (COSTS OFF) SELECT id FROM jobs WHERE done_at IS NULL AND queue = 'email' ORDER BY run_at LIMIT 5;
INSERT INTO jobs (queue, payload, run_at, dedupe_key) VALUES ('email', '{}', now(), 'welcome:7');
INSERT INTO jobs (queue, payload, run_at, dedupe_key) VALUES ('email', '{}', now(), 'welcome:7');
UPDATE jobs SET done_at = now() WHERE dedupe_key = 'welcome:7';
INSERT INTO jobs (queue, payload, run_at, dedupe_key) VALUES ('email', '{}', now(), 'welcome:7');
SELECT pg_size_pretty(pg_relation_size('jobs_pending')) AS pending_index,
pg_size_pretty(pg_relation_size('jobs')) AS table_size;المخرجات
$ psql -q -f seed.sql -f queries.sql
QUERY PLAN
---------------------------------------------
Limit
-> Index Scan using jobs_pending on jobs
Index Cond: (queue = 'email'::text)
(3 rows)
psql:queries.sql:25: ERROR: duplicate key value violates unique constraint "jobs_dedupe"
DETAIL: Key (dedupe_key)=(welcome:7) already exists.
pending_index | table_size
---------------+------------
16 kB | 6672 kB
(1 row)Index Scan using jobs_pending، من غير Sort. التكرار اترفض، وبعد ما خلصت اتقبلت تاني. والـ index بالكيلوبايت، والجدول بالميجات. الدرس الجاي: الـ pagination، وليه OFFSET بيبقى بطيء جدًّا في الصفحات البعيدة.
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