الهدف
بعد هالدرس تقدر تبني live dashboard يتحدّث تلقائيا لما مستخدم ثاني يحدّث البيانات، وتعرف الفرق بين WebSockets و Server-Sent Events و polling — وتختار الصح حسب الـ use case.
ليش هذا الحين؟
عندك roadmap و iteration process. الحين نبني feature تقني يفتح أبواب لـ collaboration و engagement: real-time updates. ترى الـ polling (كل 5 ثوان تسأل الـ server) يشتغل — بس يأكل resources و bandwidth. الـ real-time يجيب البيانات بالضبط لما تتغير، بدون waste.
الفكرة
الثلاثة خيارات:
| الطريقة | متى تستخدم | Complexity |
|---|---|---|
| Polling | أي شي، simple | Low |
| SSE (Server-Sent Events) | Server → Client بس, one-way | Medium |
| WebSockets | Bidirectional (chat, collaborative editing) | High |
لـ أغلب SaaS apps، SSE يكفي:
- Live stats/counters
- Notifications
- Dashboard refresh
WebSockets للـ chat و collaborative editing (Google Docs style).
Supabase Realtime:
Supabase يوفر real-time via PostgreSQL replication. كل تغيير في DB → event ينرسل للـ clients المشتركين. مناسب لو أصلا تستخدم Supabase. لو تستخدم Neon + Prisma، استخدم SSE.
Pattern الـ Optimistic UI + Real-time Reconciliation:
User clicks "Log habit"
→ UI updates immediately (optimistic)
→ API call fires
→ Real-time event confirms the update
→ If API failed: revert UI
هذا يعطي الـ user إحساس بالسرعة حتى لو الشبكة بطيئة.