Real-Time Communication Concepts
في request/response العادي client يبدأ كل request. Real-time systems تحتاج server يدفع events فور حدوثها، مثل notification أو live dashboard. الخيارات تختلف: polling يطلب دورياً؛ SSE stream أحادي الاتجاه من server إلى browser؛ WebSocket قناة ثنائية الاتجاه منخفضة overhead؛ SignalR abstraction يدير connections/hubs/groups ويتفاوض على transports، ويمكن أن يستخدم WebSockets أو SSE أو Long Polling حسب capabilities/configuration.
| Approach | Direction | Fit |
|---|---|---|
| Polling | Client asks repeatedly | Simple, delayed updates |
| SSE | Server → client | Notifications / event feed |
| WebSocket | Bidirectional | Custom low-level protocol |
| SignalR | Hub-based bidirectional | .NET apps needing managed real-time abstraction |
SignalR vs WebSockets vs SSE vs Polling
| Technology | Direction | Best fit |
|---|---|---|
| WebSockets | Full duplex | Custom low-level bidirectional protocol |
| SignalR | Hub abstraction over transports | .NET app real-time messaging and groups |
| SSE | Server → client | Simple event feed / progress updates |
| Polling | Client asks repeatedly | Simple low-frequency refresh |
SignalR مناسب عندما تحتاج hub methods و groups و fallback transports و client libraries. SSE أبسط لو الاتجاه server-to-client فقط. WebSockets مباشرة تعطي تحكماً أكبر لكنك ستبني protocol/reconnect/dispatch بنفسك. Polling قد يكون كافياً لو التحديث كل عدة دقائق ولا يستحق اتصالاً دائماً.
SignalR كـ Notification Channel
Pattern قوي: application service تحفظ التغيير في database، ثم تنشر notification عبر outbox/background dispatcher إلى SignalR. client عند استقبال notification يحدّث UI أو يجلب latest state من REST API. لو connection قطعت، client يعمل reconnect ثم fetch delta أو current state. بهذه الطريقة لا تعتمد على connection حية لضمان business event durability.
لو notification ضاعت، database state ما زالت صحيحة ويمكن استعادتها. لو event يجب ألا يضيع لأغراض compliance، احتفظ به في durable event store/queue. SignalR يحسن responsiveness وليس transaction guarantee.
Hubs و Hub Methods
Hub هو endpoint abstraction للرسائل؛ client ينادي server hub method، و server يرسل إلى caller أو connection أو group أو جميع العملاء. Hub instances ليست durable state store؛ غالباً لا تحتفظ بحالة business داخل instance fields لأن lifetime/activation ليس ضماناً لمشاركة state بين connections/requests.
[Authorize]
public sealed class NotificationsHub(ILogger<NotificationsHub> logger) : Hub
{
public Task JoinOrderRoom(int orderId)
=> Groups.AddToGroupAsync(
Context.ConnectionId,
$"order:{orderId}");
public Task LeaveOrderRoom(int orderId)
=> Groups.RemoveFromGroupAsync(
Context.ConnectionId,
$"order:{orderId}");
}
// From an application service, send through IHubContext:
await hubContext.Clients.Group($"order:{orderId}")
.SendAsync("OrderUpdated", new { orderId, status = "Shipped" }, token);لا تسمح للعميل ينضم لأي group بمجرد إرسال orderId قبل التحقق أن user يملك access لهذا order. Group name ليست security boundary. server-side authorization لازم يقرر membership، وقد تحتاج إزالة/إعادة تقييم membership عند تغير permissions.
Hub Methods و Groups و Clients API
Hub method هي RPC-like call من client إلى server. Server يقدر يرسل إلى caller أو others أو all أو group أو user. Group مناسب لمجموعة اتصالات مثل room أو tenant channel، لكن membership ليست authorization تلقائياً. لازم تتحقق أن المستخدم مسموح له يدخل group، ولا تثق في group name أرسله client.
[Authorize]
public sealed class OrdersHub(IOrderAccess access) : Hub
{
public async Task JoinOrder(int orderId)
{
var userId = Context.UserIdentifier;
if (userId is null ||
!await access.CanViewAsync(userId, orderId, Context.ConnectionAborted))
{
throw new HubException("Access denied.");
}
await Groups.AddToGroupAsync(
Context.ConnectionId, $"order:{orderId}");
}
}استخدم group names داخلية لا تكشف معلومات حساسة، ونظّف membership حسب lifecycle أو connection behavior. إرسال message إلى group لا يعني أن كل user فيها ما زال online أو أنه استلم الرسالة.
Connection Lifecycle و Groups و Messaging
Lifecycle events تشمل OnConnectedAsync و OnDisconnectedAsync، لكن الانقطاع المفاجئ قد يتأخر اكتشافه حسب keep-alive/client timeout. Groups logical broadcast targets؛ ليست database ولا ضماناً لتخزين الرسائل للأبد. إذا العميل offline وقت الحدث، SignalR لا يقدم durable delivery history؛ استخدم persistent notifications + catch-up query لو loss غير مقبول.
public override async Task OnConnectedAsync()
{
logger.LogInformation("SignalR connected {ConnectionId}", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
if (exception is not null)
logger.LogWarning(exception, "SignalR disconnected unexpectedly");
await base.OnDisconnectedAsync(exception);
}Connection Lifecycle و Transport Negotiation
SignalR يبدأ غالباً بطلب negotiate ثم يختار transport متاحاً حسب client/server/network: WebSockets، Server-Sent Events، أو Long Polling. الاتصال قد ينقطع بسبب mobile network switching أو proxy timeout أو sleep. لا تتعامل مع ConnectionId كهوية دائمة للمستخدم؛ reconnect قد ينشئ connection جديدة. user identity تأتي من authentication principal، وليس من ConnectionId.
Hub instance transient per invocation في النموذج المعتاد؛ لا تخزن state داخل field وتتوقع أنه سيظل موجوداً بين رسائل العميل. استخدم database/cache أو service scoped مناسبة. لا تجعل Hub هو مكان business logic؛ انقل use cases إلى application service.
Groups Lifecycle و Durability
Group membership عادة مرتبطة بالاتصال، ولا تعتبر database membership. عند reconnect قد تحتاج rejoin، وعند authorization revocation قد تحتاج إزالة connection من groups أو منعها من receiving future messages. لا تستخدم group كأنها access-control database. تحقق من user/resource permission قبل join وقبل أي hub command حساس.
SignalR message delivery ليست durable queue. لو event مهم لازم لا يضيع، خزنه في database/broker مع sequence/cursor، واستخدم SignalR كـ notification channel يخبر client أن هناك تحديثاً. العميل عند reconnect يستطيع fetch missed changes من API. ده pattern أكثر أماناً من الاعتماد على live connection وحدها.
Authentication و Authorization و Reconnection
SignalR endpoint يخضع ASP.NET Core authentication/authorization. يمكن وضع [Authorize] على Hub أو method، أو استخدام policies. في browser WebSocket/SSE بعض clients يضطرون لإرسال access token عبر query string بسبب API restrictions؛ احمِ transport بـ HTTPS، قلل logging لـ URL/query strings، ولا تسمح بتسريب token في access logs. تفصيل JWT ضمن مجلد security.
Reconnection لا تعني استعادة نفس ConnectionId ولا أن group membership محفوظة دائماً بعد إعادة الاتصال. client يجب أن يعيد الانضمام للمجموعات وأن يسترجع missed state عبر API. استخدم automatic reconnect strategy مع backoff، ولا تجعل clients تعمل reconnect storm عند انقطاع service جماعي.
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/notifications", {
accessTokenFactory: () => authStore.getAccessToken()
})
.withAutomaticReconnect([0, 2000, 10000, 30000])
.build();
connection.on("OrderUpdated", update => renderOrder(update));
connection.onreconnected(async () => {
await connection.invoke("JoinOrderRoom", currentOrderId);
await refreshOrderFromApi(currentOrderId); // catch up missed state
});
await connection.start();Authorization على مستوى Group
Client-supplied identifiers ليست authorization. قبل Groups.AddToGroupAsync لازم تتحقق server-side من أن user له access إلى order/customer/tenant المحدد. لو permissions تغيرت، فكر هل يجب إزالة connections من groups أو رفض كل outgoing message بناءً على policy. لا ترسل message إلى group broad لو فيها PII، وابتعد عن predictable group names كوسيلة سرية.
Hub methods public surface مثل API endpoints: validate arguments، enforce authorization، limit message size/rate، وراجع method invocation permissions. لا تسمح للعميل ينادي server method باسم arbitrary أو يمرر tenantId وتثق به دون مقارنة مع claims/owned resource.
Client Reconnection و Message Delivery
Automatic reconnect في client يحتاج configuration، وقد يمر بحالة reconnecting ثم reconnected أو close. بعد reconnect قد يتغير ConnectionId، ولازم تعيد join groups إذا لم يكن عندك state restoration strategy. لا تفترض أن الرسائل التي أُرسلت أثناء الانقطاع ستصل تلقائياً؛ SignalR ليس durable message broker.
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/orders", { accessTokenFactory: () => getAccessToken() })
.withAutomaticReconnect([0, 2000, 10000, 30000])
.build();
connection.onreconnected(async () => {
await connection.invoke("JoinOrder", currentOrderId);
});
connection.on("OrderUpdated", payload => renderOrder(payload));
await connection.start();
await connection.invoke("JoinOrder", currentOrderId);لو client يحتاج ضمان عدم فقد events، استخدم sequence numbers/resume cursor مع persistence أو broker/event store. إعادة الاتصال وحدها لا تعيد الأحداث التي فاتت.
Clients.User و UserIdentifier
المستخدم الواحد قد يكون عنده أكثر من connection: موبايل وتاب browser. Clients.User(userId) يستهدف connections المرتبطة بنفس user identifier، بينما Clients.Client(connectionId) يستهدف connection واحدة فقط. تأكد من اختيار UserIdentifier claim المناسب، ولا تستخدم email متغير كمعرف دائم لو عندك immutable user ID.
لو عندك multi-tenant app، راجع هل user ID عالمي أم scoped داخل tenant. Group names لا ينبغي أن تسمح لمستخدم من tenant آخر بالانضمام إلى بيانات غيره. membership قرار authorization، والرسالة المرسلة إلى group لا تحل محل permission checks على command.
UserIdentifier و Multiple Connections
SignalR يحدد user identifier افتراضياً من claim معينة حسب authentication setup. لو عندك custom identity provider، يمكن تخصيص IUserIdProvider. اختار claim ثابتة وغير قابلة للتغيير مثل internal user ID، وليس display name. اختبر وجود أكثر من connection لنفس user، وسلوك logout/token expiration، و tenant isolation.
لا ترسل secrets أو تفاصيل حساسة في broadcast messages لمجرد أن client authenticated. Authorization على كل command، وتحديد audience لكل notification، ومراجعة payload minimization ضرورية.
Error Handling و Angular Client Integration
لا ترسل exception stack trace للعميل. استخدم stable error events/codes، logs correlation، و recovery policy. في Angular/TypeScript غلف HubConnection داخل service singleton مناسب، أدر subscriptions cleanup، ولا تنشئ connection لكل component. تعامل مع reconnect state و authorization expiry وتحديث token.
@Injectable({ providedIn: 'root' })
export class NotificationsService {
private connection?: signalR.HubConnection;
readonly orderUpdates = new Subject<OrderUpdate>();
async connect(): Promise<void> {
this.connection = new signalR.HubConnectionBuilder()
.withUrl('/hubs/notifications', {
accessTokenFactory: () => this.auth.accessToken()
})
.withAutomaticReconnect()
.build();
this.connection.on('OrderUpdated', value => this.orderUpdates.next(value));
await this.connection.start();
}
async disconnect(): Promise<void> {
await this.connection?.stop();
this.connection = undefined;
}
}الكود sketch يوضح ownership؛ في التطبيق الفعلي أضف guards لمنع start متكرر، handling لـ failed start، retry/backoff، lifecycle logout، و cleanup للـ Subject subscriptions.
Client Integration مع TypeScript/Angular
في Angular، لا تنشئ HubConnection في كل component؛ اعمل service مسؤول عن إنشاء الاتصال وبدءه وإيقافه وإعادة الاشتراك. component يشترك في observable أو callback ويتخلص من subscription عند destroy. افصل connection lifecycle عن UI rendering حتى لا تتكرر الاتصالات مع navigation.
@Injectable({ providedIn: 'root' })
export class OrdersRealtimeService {
private connection?: signalR.HubConnection;
private readonly updatesSubject = new Subject<OrderUpdate>();
readonly updates$ = this.updatesSubject.asObservable();
async connect(): Promise<void> {
if (this.connection?.state === signalR.HubConnectionState.Connected) return;
this.connection = new signalR.HubConnectionBuilder()
.withUrl('/hubs/orders')
.withAutomaticReconnect()
.build();
this.connection.on('OrderUpdated', value =>
this.updatesSubject.next(value as OrderUpdate));
await this.connection.start();
}
async disconnect(): Promise<void> {
await this.connection?.stop();
}
}المثال يوضح structure فقط؛ production يحتاج error handling و token provider و reconnect group rejoin و dispose lifecycle. لا تعتمد على TypeScript cast كأنه runtime validation؛ server payload contract يجب أن يكون معروفاً ومختبراً.
Security و Operational Limits
الاتصال الطويل يستهلك connection slots و memory حتى لو messages قليلة. حدد limits على message size و concurrent connections و group membership، وراقب connection count و reconnect rate و send failures. لا تبعث sensitive payload لكل clients في group عام. اعمل authorization على كل command يغير state، وليس فقط عند فتح connection.
في browser clients، token في query string قد يظهر في reverse proxy/access logs. لو اضطررت لاستخدامه مع WebSockets/SSE، restrict extraction للـ hub path واحذف query token من logs. استخدم HTTPS، token lifetime مناسب، وتجديد token/reconnect behavior واضح.
Scale-Out: Backplane vs Azure SignalR
مع instance واحدة، connections متصلة بها. عند scale-out عبر عدة instances، client قد يتصل بـ instance A والـ publisher/Hub request يمر على B. Backplane مثل Redis يوزع messages بين instances؛ لكنه لا يخزن رسائل durable ولا يحل كل مشاكل sticky sessions/transport. Azure SignalR Service ينقل connection management إلى managed service ويخفف تعقيد scale، مقابل تكلفة وخدمات خارجية واعتماد تشغيلي.
ضع limits للاتصالات والـ message size، راقب connection count و reconnects و send failures. في multi-region topology، latency و routing و service mode تؤثر على تجربة العميل.
Authentication و Scale-out و Backplane
مع أكثر من server instance، connection موجودة على instance معينة. Redis backplane يمرر SignalR messages بين instances، لكنه لا يحوّل كل connection state إلى distributed durable state. Azure SignalR Service يقدم managed connection scale-out model. في بعض deployment setups تحتاج sticky sessions حسب transport/configuration؛ راجع hosting guidance.
Authentication عادة تستخدم cookie أو bearer token. في browser WebSockets/SSE، access token قد ينتقل عبر query string في بعض client configurations بسبب قيود headers؛ لازم تحمي logs حتى لا تسجل query token، وتحدد token extraction على hub routes فقط. Authorization على Hub أو Hub method، لكن resource-specific checks تظل مطلوبة عند الانضمام إلى group أو طلب data.
Redis Backplane vs Azure SignalR Service
Redis backplane يوزع messages بين SignalR server instances؛ كل instance ما زالت تدير اتصالات clients المتصلة بها. Redis يصبح dependency تشغيلية تحتاج availability/latency/monitoring. Azure SignalR Service يدير connection infrastructure ويقلل عبء scale-out على app instances، لكنه يضيف service dependency وتكلفة/region considerations. اختار بناءً على hosting model و traffic و operational skills.
اختبر scale-out مع أكثر من app instance، reconnect، group membership، sticky session requirements حسب transport/deployment، وفشل backplane. لا تفترض أن local single-instance test يثبت production behavior.
Backplane و Azure SignalR: حدود الضمانات
Redis backplane يوزع hub messages بين server nodes لكنه لا يجعل SignalR queue durable. بعض hosting topologies تحتاج sticky sessions حتى تظل connection requests المرتبطة بـ negotiation/transport على نفس node، مع استثناءات حسب WebSockets-only configuration والـ scale service. Azure SignalR يدير connection routing ويزيل أجزاء من عبء scale، لكنه يضيف dependency على managed service وحدود quotas/regions/cost. اختبر reconnect storms و message fan-out وعدد connections المتوقع.
عندما تكون delivery ضمانية business-critical (مثلاً دفع أو تنبيه قانوني)، خزّن الحدث/notification في database أو broker ثم استخدم SignalR كـ low-latency push hint؛ client يعمل fetch/catch-up ويقرأ durable state. لا تعامل socket delivery كبديل عن transactional messaging.
SignalR Reliability Checklist
- ConnectionId ليس user identity دائمة.
- Reconnection قد تتطلب إعادة join groups.
- Hub instance ليست state store.
- Authorize group membership and every state-changing command.
- Use stable user identifier for multi-device targeting.
- SignalR is not durable message storage.
- Persist important events and let clients catch up through API.
- Monitor active connections, reconnects, send failures, و scale-out.
فكر في SignalR كقناة realtime لإخبار العميل أن شيئاً تغير، وليس بالضرورة المصدر الوحيد للحقيقة. API/database تظل مصدر الحقيقة، والعميل يستطيع إعادة المزامنة بعد انقطاع الاتصال.
المستوى المطلوب من SignalR
تقدر تشرح Hub و connection lifecycle و groups و client messaging و auth/reconnect، وتفهم أن ConnectionId ليس user identity وأن SignalR ليس durable message broker. تعرف متى تستخدم WebSockets أو SSE أو polling، وما دور Redis backplane أو Azure SignalR Service في scale-out. في تطبيق حقيقي، احفظ business events في durable storage واستخدم SignalR كقناة notification.
مثال end-to-end: إشعار «المستند جاهز» من الـ worker للـ Angular
السيناريو الأشهر في الـ AI SaaS: المستخدم رفع PDF، الـ ingestion worker خلص الـ chunking والـ embeddings بعد دقيقة، والـ UI لازم يعرف من غير polling. الـ worker مش جوه الـ Hub، فبيستخدم IHubContext.
[Authorize]
public sealed class NotificationsHub : Hub<INotificationsClient>
{
public override async Task OnConnectedAsync()
{
var tid = Context.User!.FindFirstValue("tid")!; // from the validated token, never from the client
await Groups.AddToGroupAsync(Context.ConnectionId, $"tenant:{tid}");
await base.OnConnectedAsync();
}
}
public interface INotificationsClient { Task DocumentReady(DocumentReadyDto dto); }
public sealed record DocumentReadyDto(Guid DocumentId, string Status);
// inside the ingestion job
public sealed class DocumentProcessedNotifier(IHubContext<NotificationsHub, INotificationsClient> hub)
{
public Task NotifyAsync(Guid tenantId, Guid userId, Guid docId, CancellationToken ct) =>
hub.Clients.User(userId.ToString()).DocumentReady(new(docId, "ready")); // all tabs/devices of that user
}@Injectable({ providedIn: 'root' })
export class NotificationsService {
private auth = inject(AuthService);
private docs = inject(DocumentsStore);
readonly state = signal<'connecting' | 'connected' | 'reconnecting' | 'disconnected'>('disconnected');
private conn = new signalR.HubConnectionBuilder()
.withUrl('/hubs/notifications', { accessTokenFactory: () => this.auth.accessToken() }) // token via query string for WS
.withAutomaticReconnect([0, 2000, 10000, 30000])
.build();
constructor() {
this.conn.on('DocumentReady', (d: { documentId: string }) => this.docs.refresh(d.documentId)); // re-fetch truth
this.conn.onreconnecting(() => this.state.set('reconnecting'));
this.conn.onreconnected(() => { this.state.set('connected'); this.docs.refreshAll(); }); // we may have missed events
this.conn.onclose(() => this.state.set('disconnected'));
}
async start() { this.state.set('connecting'); await this.conn.start(); this.state.set('connected'); }
}نقطتين بيفرقوا: (1) SignalR مش durable: لو المستخدم offline لحظة الإرسال، الرسالة ضاعت. عشان كده بعد الـ reconnect بنعمل refresh، والحالة الحقيقية في الـ DB. (2) الـ access token في الـ query string للـ WebSockets بيظهر في logs الـ proxy أحيانًا؛ خلي الـ token قصير العمر وفلتر الـ logs.
SignalR ولا SSE ولا WebSockets خام؟
| SSE | SignalR | WebSockets خام | |
|---|---|---|---|
| الاتجاه | server → client | الاتنين | الاتنين |
| البنية | HTTP عادي، text/event-stream | Hubs، groups، reconnect، fallback transports | انت بتبني كل حاجة |
| Scale-out | أي HTTP infra | backplane أو Azure SignalR Service | انت بتحله |
| أنسب لـ | streaming إجابة LLM (token by token)، progress | إشعارات، collaboration، dashboards live | بروتوكولات خاصة، ألعاب |
عشان كده الـ Capstone بيستخدم SSE لـ streaming الـ chat (request واحد، اتجاه واحد، بيعدي من أي proxy) وSignalR للإشعارات (المستند جاهز، الـ approval اتوافق عليه). ده مشروح في AI Product Engineering.
أخطاء شائعة في SignalR
- الاعتماد على SignalR كـ message queue: مفيش ضمان توصيل ولا ترتيب عبر reconnects.
- إرسال بيانات كاملة حساسة في الرسالة بدل «id + حدث» والـ client يجيب بصلاحياته.
- Group names من input المستخدم (
JoinGroup("tenant:other")) من غير authorization. - Scale-out من غير backplane أو sticky sessions ← رسايل بتوصل لنص المستخدمين بس.
- تخزين state في Hub instance: الـ Hub transient — كل method call instance جديد.
Knowledge Check
هل SignalR group تضمن أن العميل يستقبل event وهو offline؟
هل ConnectionId يظل نفسه بعد reconnect؟
متى تختار SSE بدلاً من SignalR؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
خريطة التغطية: 16 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.