
Previous Article: Background Jobs Revolution: Mastering Automated Processing in ASP.NET Core (Part - 30 of 40)
Table of Contents
Introduction to Real-Time Communication
Understanding SignalR Fundamentals
Building Real-Time Chat Applications
SignalR Hubs and Groups
Scaling SignalR Applications
gRPC Core Concepts
Building High-Performance gRPC Services
gRPC Streaming Patterns
Real-World Case Study: Live Dashboard
Security and Authentication
Performance Optimization
Testing and Debugging
Production Deployment
Conclusion
1. Introduction to Real-Time Communication
Real-time communication has transformed how users interact with web applications. From live chat systems to collaborative editing tools and real-time dashboards, the demand for instant data updates has never been higher. ASP.NET Core provides two powerful technologies for building real-time applications: SignalR for WebSocket-based communication and gRPC for high-performance service-to-service communication.
The Evolution of Real-Time Web
Traditional web applications followed a request-response pattern where clients had to poll servers for updates. This approach was inefficient and created latency. Modern real-time technologies enable:
Instant Updates : Push data to clients immediately when changes occur
Bidirectional Communication : Both client and server can initiate communication
Reduced Latency : Eliminate polling overhead with persistent connections
Better User Experience : Create responsive, interactive applications
When to Use SignalR vs gRPC
csharp
public class CommunicationChoiceGuide
{
public CommunicationTechnology ChooseTechnology(ApplicationRequirements requirements)
{
if (requirements.NeedBrowserClientSupport && requirements.RealTimeUpdates)
{
return CommunicationTechnology.SignalR;
}
else if (requirements.HighPerformance && requirements.InternalServiceCommunication)
{
return CommunicationTechnology.gRPC;
}
else if (requirements.BothBrowserAndServiceCommunication)
{
return CommunicationTechnology.Hybrid;
}
return CommunicationTechnology.RestAPI;
}
}
public enum CommunicationTechnology
{
SignalR, // Web browsers, mobile apps, real-time features
gRPC, // Microservices, internal APIs, high-performance
Hybrid, // Combined approach
RestAPI // Traditional HTTP APIs
}
Real-World Applications
Live Chat Systems : Customer support, team collaboration
Real-Time Dashboards : Stock trading, IoT monitoring, analytics
Collaborative Tools : Google Docs-like editing, design tools
Gaming : Multiplayer games, live scores
Notifications : Live updates, alerts, announcements
Financial Systems : Live trading, price updates
2. Understanding SignalR Fundamentals
SignalR Architecture Overview
SignalR provides an abstraction over real-time transports, automatically choosing the best available transport method:
WebSockets (Preferred): Full-duplex communication over a single TCP connection
Server-Sent Events : One-way communication from server to client
Long Polling : Fallback for environments that don't support newer transports
Basic SignalR Setup
csharp
// Program.cs configuration
using Microsoft.AspNetCore.SignalR;
var builder = WebApplication.CreateBuilder(args);
// Add SignalR services
builder.Services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
options.KeepAliveInterval = TimeSpan.FromSeconds(15);
options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
});
// Add CORS for cross-origin requests
builder.Services.AddCors(options =>
{
options.AddPolicy("SignalRPolicy", policy =>
{
policy.WithOrigins("https://localhost:3000", "https://myapp.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline
app.UseCors("SignalRPolicy");
app.UseRouting();
app.MapHub<ChatHub>("/chathub");
app.MapHub<NotificationHub>("/notifications");
app.MapHub<DashboardHub>("/dashboard");
app.Run();
Creating Your First SignalR Hub
csharp
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
private static readonly Dictionary<string, string> _userConnections = new();
// Client calls this method to join the chat
public async Task JoinChat(string userName)
{
_userConnections[Context.ConnectionId] = userName;
// Notify all clients that a user joined
await Clients.All.SendAsync("UserJoined", userName, DateTime.Now.ToString());
// Send current user list to the new user
await Clients.Caller.SendAsync("CurrentUsers", _userConnections.Values.ToArray());
await Clients.Caller.SendAsync("ReceiveMessage", "System",
$"Welcome to the chat, {userName}!");
}
// Client calls this method to send a message
public async Task SendMessage(string user, string message)
{
if (string.IsNullOrWhiteSpace(message))
return;
// Broadcast message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message, DateTime.Now.ToString());
}
// Client calls this method to send a private message
public async Task SendPrivateMessage(string targetUser, string message)
{
var sender = _userConnections[Context.ConnectionId];
var targetConnection = _userConnections
.FirstOrDefault(x => x.Value == targetUser).Key;
if (targetConnection != null)
{
await Clients.Client(targetConnection).SendAsync("ReceivePrivateMessage",
sender, message, DateTime.Now.ToString());
await Clients.Caller.SendAsync("ReceivePrivateMessage",
$"You to {targetUser}", message, DateTime.Now.ToString());
}
}
// Handle client connection
public override async Task OnConnectedAsync()
{
await Clients.Caller.SendAsync("ReceiveMessage", "System",
"Connected to chat server!");
await base.OnConnectedAsync();
}
// Handle client disconnection
public override async Task OnDisconnectedAsync(Exception? exception)
{
if (_userConnections.TryGetValue(Context.ConnectionId, out var userName))
{
_userConnections.Remove(Context.ConnectionId);
await Clients.All.SendAsync("UserLeft", userName, DateTime.Now.ToString());
}
await base.OnDisconnectedAsync(exception);
}
}
JavaScript Client Implementation
html
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Chat</title>
<style>
.chat-container { max-width: 800px; margin: 0 auto; padding: 20px; }
.messages { height: 400px; border: 1px solid #ccc; overflow-y: scroll; padding: 10px; }
.message { margin-bottom: 10px; padding: 8px; border-radius: 5px; }
.system { background-color: #f0f0f0; color: #666; }
.user { background-color: #e3f2fd; }
.private { background-color: #fff3e0; border-left: 3px solid #ff9800; }
.input-area { margin-top: 20px; display: flex; gap: 10px; }
input, button { padding: 10px; font-size: 16px; }
</style>
</head>
<body>
<div class="chat-container">
<h1>Real-Time Chat</h1>
<div class="connection-status">
<span id="status">Disconnected</span>
</div>
<div class="user-setup" id="userSetup">
<input type="text" id="userNameInput" placeholder="Enter your name" />
<button onclick="joinChat()">Join Chat</button>
</div>
<div class="chat-area" id="chatArea" style="display: none;">
<div class="users-online">
<h3>Online Users: <span id="userCount">0</span></h3>
<div id="userList"></div>
</div>
<div id="messages" class="messages"></div>
<div class="input-area">
<input type="text" id="messageInput" placeholder="Type your message..." />
<button onclick="sendMessage()">Send</button>
<select id="userSelect">
<option value="">Everyone</option>
</select>
<button onclick="sendPrivateMessage()">Send Private</button>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.8/signalr.min.js"></script>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) // Reconnect intervals
.configureLogging(signalR.LogLevel.Information)
.build();
let currentUser = '';
// Connection event handlers
connection.onreconnecting(error => {
console.log('Connection lost. Reconnecting...', error);
updateStatus('Reconnecting...', 'orange');
});
connection.onreconnected(connectionId => {
console.log('Connection reestablished.');
updateStatus('Connected', 'green');
if (currentUser) {
connection.invoke("JoinChat", currentUser);
}
});
connection.onclose(error => {
console.log('Connection closed.', error);
updateStatus('Disconnected', 'red');
});
// Message handlers
connection.on("ReceiveMessage", (user, message, timestamp) => {
addMessage(user, message, timestamp, 'user');
});
connection.on("ReceivePrivateMessage", (user, message, timestamp) => {
addMessage(user, message, timestamp, 'private');
});
connection.on("UserJoined", (userName, timestamp) => {
addMessage('System', `${userName} joined the chat`, timestamp, 'system');
});
connection.on("UserLeft", (userName, timestamp) => {
addMessage('System', `${userName} left the chat`, timestamp, 'system');
});
connection.on("CurrentUsers", (users) => {
updateUserList(users);
});
// UI functions
function updateStatus(message, color) {
const statusElement = document.getElementById('status');
statusElement.textContent = message;
statusElement.style.color = color;
}
function addMessage(user, message, timestamp, type) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
const time = new Date(timestamp).toLocaleTimeString();
messageDiv.innerHTML = `
<strong>${user}</strong>
<small>(${time})</small>:
${message}
`;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function updateUserList(users) {
const userList = document.getElementById('userList');
const userSelect = document.getElementById('userSelect');
userList.innerHTML = '';
userSelect.innerHTML = '<option value="">Everyone</option>';
users.forEach(user => {
if (user !== currentUser) {
// Add to online users list
const userElement = document.createElement('div');
userElement.textContent = user;
userList.appendChild(userElement);
// Add to private message dropdown
const option = document.createElement('option');
option.value = user;
option.textContent = user;
userSelect.appendChild(option);
}
});
document.getElementById('userCount').textContent = users.length;
}
// Chat functions
async function joinChat() {
const userName = document.getElementById('userNameInput').value.trim();
if (!userName) return;
try {
await connection.start();
await connection.invoke("JoinChat", userName);
currentUser = userName;
document.getElementById('userSetup').style.display = 'none';
document.getElementById('chatArea').style.display = 'block';
updateStatus('Connected', 'green');
} catch (err) {
console.error('Failed to join chat:', err);
alert('Failed to join chat. Please try again.');
}
}
async function sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value.trim();
if (!message) return;
try {
await connection.invoke("SendMessage", currentUser, message);
messageInput.value = '';
} catch (err) {
console.error('Failed to send message:', err);
}
}
async function sendPrivateMessage() {
const messageInput = document.getElementById('messageInput');
const userSelect = document.getElementById('userSelect');
const targetUser = userSelect.value;
const message = messageInput.value.trim();
if (!targetUser || !message) return;
try {
await connection.invoke("SendPrivateMessage", targetUser, message);
messageInput.value = '';
} catch (err) {
console.error('Failed to send private message:', err);
}
}
// Handle Enter key
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
const userSelect = document.getElementById('userSelect');
if (userSelect.value === '') {
sendMessage();
} else {
sendPrivateMessage();
}
}
});
// Initialize connection
async function startConnection() {
try {
await connection.start();
updateStatus('Connected', 'green');
} catch (err) {
console.error('SignalR Connection Error: ', err);
updateStatus('Connection Failed', 'red');
setTimeout(startConnection, 5000);
}
}
startConnection();
</script>
</body>
</html>
Advanced SignalR Hub with Strong Typing
csharp
// Strongly typed hub interface for better IntelliSense
public interface IChatClient
{
Task ReceiveMessage(string user, string message, string timestamp);
Task ReceivePrivateMessage(string fromUser, string message, string timestamp);
Task UserJoined(string userName, string timestamp);
Task UserLeft(string userName, string timestamp);
Task CurrentUsers(string[] users);
Task MessageDelivered(string messageId, string timestamp);
Task UserTyping(string userName, bool isTyping);
}
// Strongly typed hub
public class AdvancedChatHub : Hub<IChatClient>
{
private readonly IChatRepository _chatRepository;
private readonly ILogger<AdvancedChatHub> _logger;
public AdvancedChatHub(IChatRepository chatRepository, ILogger<AdvancedChatHub> logger)
{
_chatRepository = chatRepository;
_logger = logger;
}
public async Task JoinChat(string userName, string room = "general")
{
var user = new ChatUser
{
ConnectionId = Context.ConnectionId,
UserName = userName,
Room = room,
JoinedAt = DateTime.UtcNow
};
await _chatRepository.AddUserAsync(user);
await Groups.AddToGroupAsync(Context.ConnectionId, room);
// Notify group about new user
await Clients.Group(room).UserJoined(userName, DateTime.UtcNow.ToString());
// Send room history to the new user
var roomHistory = await _chatRepository.GetRoomHistoryAsync(room, 50);
foreach (var message in roomHistory)
{
await Clients.Caller.ReceiveMessage(message.UserName, message.Content, message.SentAt.ToString());
}
// Send current room users
var roomUsers = await _chatRepository.GetRoomUsersAsync(room);
await Clients.Caller.CurrentUsers(roomUsers.Select(u => u.UserName).ToArray());
_logger.LogInformation("User {UserName} joined room {Room}", userName, room);
}
public async Task SendMessageToRoom(string room, string message)
{
if (string.IsNullOrWhiteSpace(message))
return;
var user = await _chatRepository.GetUserAsync(Context.ConnectionId);
if (user == null) return;
var chatMessage = new ChatMessage
{
Id = Guid.NewGuid().ToString(),
UserName = user.UserName,
Room = room,
Content = message,
SentAt = DateTime.UtcNow
};
await _chatRepository.AddMessageAsync(chatMessage);
// Broadcast to room
await Clients.Group(room).ReceiveMessage(user.UserName, message, DateTime.UtcNow.ToString());
_logger.LogDebug("Message sent to room {Room} by {User}", room, user.UserName);
}
public async Task StartTyping(string room)
{
var user = await _chatRepository.GetUserAsync(Context.ConnectionId);
if (user != null)
{
await Clients.OthersInGroup(room).UserTyping(user.UserName, true);
}
}
public async Task StopTyping(string room)
{
var user = await _chatRepository.GetUserAsync(Context.ConnectionId);
if (user != null)
{
await Clients.OthersInGroup(room).UserTyping(user.UserName, false);
}
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var user = await _chatRepository.GetUserAsync(Context.ConnectionId);
if (user != null)
{
await _chatRepository.RemoveUserAsync(Context.ConnectionId);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, user.Room);
await Clients.Group(user.Room).UserLeft(user.UserName, DateTime.UtcNow.ToString());
_logger.LogInformation("User {UserName} left room {Room}", user.UserName, user.Room);
}
await base.OnDisconnectedAsync(exception);
}
}
// Supporting classes
public class ChatUser
{
public string ConnectionId { get; set; } = string.Empty;
public string UserName { get; set; } = string.Empty;
public string Room { get; set; } = "general";
public DateTime JoinedAt { get; set; }
}
public class ChatMessage
{
public string Id { get; set; } = string.Empty;
public string UserName { get; set; } = string.Empty;
public string Room { get; set; } = "general";
public string Content { get; set; } = string.Empty;
public DateTime SentAt { get; set; }
}
public interface IChatRepository
{
Task AddUserAsync(ChatUser user);
Task<ChatUser?> GetUserAsync(string connectionId);
Task RemoveUserAsync(string connectionId);
Task AddMessageAsync(ChatMessage message);
Task<List<ChatMessage>> GetRoomHistoryAsync(string room, int maxMessages);
Task<List<ChatUser>> GetRoomUsersAsync(string room);
}
public class InMemoryChatRepository : IChatRepository
{
private readonly ConcurrentDictionary<string, ChatUser> _users = new();
private readonly ConcurrentBag<ChatMessage> _messages = new();
public Task AddUserAsync(ChatUser user)
{
_users[user.ConnectionId] = user;
return Task.CompletedTask;
}
public Task<ChatUser?> GetUserAsync(string connectionId)
{
_users.TryGetValue(connectionId, out var user);
return Task.FromResult(user);
}
public Task RemoveUserAsync(string connectionId)
{
_users.TryRemove(connectionId, out _);
return Task.CompletedTask;
}
public Task AddMessageAsync(ChatMessage message)
{
_messages.Add(message);
return Task.CompletedTask;
}
public Task<List<ChatMessage>> GetRoomHistoryAsync(string room, int maxMessages)
{
var history = _messages
.Where(m => m.Room == room)
.OrderByDescending(m => m.SentAt)
.Take(maxMessages)
.OrderBy(m => m.SentAt)
.ToList();
return Task.FromResult(history);
}
public Task<List<ChatUser>> GetRoomUsersAsync(string room)
{
var users = _users.Values
.Where(u => u.Room == room)
.ToList();
return Task.FromResult(users);
}
}
3. Building Real-Time Chat Applications
Complete Chat Application Architecture
// Message types for different chat features
public abstract class ChatMessageBase
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Type { get; set; } = string.Empty;
public string RoomId { get; set; } = string.Empty;
public string Sender { get; set; } = string.Empty;
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
}
public class TextMessage : ChatMessageBase
{
public string Content { get; set; } = string.Empty;
public string? ReplyTo { get; set; }
}
public class ImageMessage : ChatMessageBase
{
public string ImageUrl { get; set; } = string.Empty;
public string? Caption { get; set; }
public long FileSize { get; set; }
}
public class SystemMessage : ChatMessageBase
{
public string Action { get; set; } = string.Empty; // "user_joined", "user_left", "room_created"
public string Data { get; set; } = string.Empty;
}
public class TypingNotification : ChatMessageBase
{
public bool IsTyping { get; set; }
}
// Enhanced chat hub with multiple rooms and rich messages
public class EnterpriseChatHub : Hub<IChatClient>
{
private readonly IChatService _chatService;
private readonly ILogger<EnterpriseChatHub> _logger;
public EnterpriseChatHub(IChatService chatService, ILogger<EnterpriseChatHub> logger)
{
_chatService = chatService;
_logger = logger;
}
public async Task<JoinRoomResult> JoinRoom(string roomId, string userName)
{
try
{
var user = new ChatUser
{
ConnectionId = Context.ConnectionId,
UserName = userName,
RoomId = roomId,
JoinedAt = DateTime.UtcNow
};
await _chatService.AddUserToRoomAsync(user);
await Groups.AddToGroupAsync(Context.ConnectionId, roomId);
// Notify room
await Clients.Group(roomId).UserJoined(userName, DateTime.UtcNow.ToString());
// Get room state
var roomState = await _chatService.GetRoomStateAsync(roomId);
_logger.LogInformation("User {UserName} joined room {RoomId}", userName, roomId);
return new JoinRoomResult
{
Success = true,
RoomState = roomState,
Message = $"Joined room {roomId} successfully"
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error joining room {RoomId} for user {UserName}", roomId, userName);
return new JoinRoomResult
{
Success = false,
Message = "Failed to join room"
};
}
}
public async Task SendTextMessage(string roomId, string content, string? replyTo = null)
{
var user = await _chatService.GetUserAsync(Context.ConnectionId);
if (user == null || user.RoomId != roomId) return;
var message = new TextMessage
{
RoomId = roomId,
Sender = user.UserName,
Content = content,
ReplyTo = replyTo
};
await _chatService.SaveMessageAsync(message);
await Clients.Group(roomId).ReceiveMessage(user.UserName, content, DateTime.UtcNow.ToString());
_logger.LogDebug("Text message sent to room {RoomId} by {User}", roomId, user.UserName);
}
public async Task SendImageMessage(string roomId, string imageUrl, string caption, long fileSize)
{
var user = await _chatService.GetUserAsync(Context.ConnectionId);
if (user == null || user.RoomId != roomId) return;
var message = new ImageMessage
{
RoomId = roomId,
Sender = user.UserName,
ImageUrl = imageUrl,
Caption = caption,
FileSize = fileSize
};
await _chatService.SaveMessageAsync(message);
// For image messages, we might want a different client method
await Clients.Group(roomId).ReceiveImageMessage(
user.UserName, imageUrl, caption, fileSize, DateTime.UtcNow.ToString());
_logger.LogDebug("Image message sent to room {RoomId} by {User}", roomId, user.UserName);
}
public async Task NotifyTyping(string roomId, bool isTyping)
{
var user = await _chatService.GetUserAsync(Context.ConnectionId);
if (user != null && user.RoomId == roomId)
{
await Clients.OthersInGroup(roomId).UserTyping(user.UserName, isTyping);
}
}
public async Task<RoomHistory> GetMessageHistory(string roomId, int skip = 0, int take = 50)
{
var user = await _chatService.GetUserAsync(Context.ConnectionId);
if (user == null || user.RoomId != roomId)
throw new HubException("User not in room");
return await _chatService.GetMessageHistoryAsync(roomId, skip, take);
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var user = await _chatService.GetUserAsync(Context.ConnectionId);
if (user != null)
{
await _chatService.RemoveUserFromRoomAsync(Context.ConnectionId);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, user.RoomId);
await Clients.Group(user.RoomId).UserLeft(user.UserName, DateTime.UtcNow.ToString());
_logger.LogInformation("User {UserName} left room {RoomId}", user.UserName, user.RoomId);
}
await base.OnDisconnectedAsync(exception);
}
}
public class JoinRoomResult
{
public bool Success { get; set; }
public RoomState? RoomState { get; set; }
public string Message { get; set; } = string.Empty;
}
public class RoomState
{
public string RoomId { get; set; } = string.Empty;
public string RoomName { get; set; } = string.Empty;
public List<string> OnlineUsers { get; set; } = new();
public List<ChatMessageBase> RecentMessages { get; set; } = new();
public int TotalMessages { get; set; }
}
public class RoomHistory
{
public List<ChatMessageBase> Messages { get; set; } = new();
public bool HasMore { get; set; }
public int TotalCount { get; set; }
}
Chat Service Implementation
csharp
public interface IChatService
{
Task AddUserToRoomAsync(ChatUser user);
Task<ChatUser?> GetUserAsync(string connectionId);
Task RemoveUserFromRoomAsync(string connectionId);
Task SaveMessageAsync(ChatMessageBase message);
Task<RoomState> GetRoomStateAsync(string roomId);
Task<RoomHistory> GetMessageHistoryAsync(string roomId, int skip, int take);
Task<List<ChatRoom>> GetAvailableRoomsAsync();
Task<ChatRoom> CreateRoomAsync(string roomName, string createdBy);
}
public class ChatService : IChatService
{
private readonly IChatRepository _repository;
private readonly ILogger<ChatService> _logger;
public ChatService(IChatRepository repository, ILogger<ChatService> logger)
{
_repository = repository;
_logger = logger;
}
public async Task AddUserToRoomAsync(ChatUser user)
{
await _repository.AddUserAsync(user);
_logger.LogDebug("User {UserName} added to room {RoomId}", user.UserName, user.RoomId);
}
public async Task<ChatUser?> GetUserAsync(string connectionId)
{
return await _repository.GetUserAsync(connectionId);
}
public async Task RemoveUserFromRoomAsync(string connectionId)
{
await _repository.RemoveUserAsync(connectionId);
}
public async Task SaveMessageAsync(ChatMessageBase message)
{
await _repository.AddMessageAsync(message);
// You could add additional logic here:
// - Check for profanity
// - Update room last activity
// - Trigger notifications
// - Save to persistent storage
}
public async Task<RoomState> GetRoomStateAsync(string roomId)
{
var room = await _repository.GetRoomAsync(roomId);
var users = await _repository.GetRoomUsersAsync(roomId);
var recentMessages = await _repository.GetRecentMessagesAsync(roomId, 50);
var totalMessages = await _repository.GetRoomMessageCountAsync(roomId);
return new RoomState
{
RoomId = roomId,
RoomName = room?.Name ?? roomId,
OnlineUsers = users.Select(u => u.UserName).ToList(),
RecentMessages = recentMessages,
TotalMessages = totalMessages
};
}
public async Task<RoomHistory> GetMessageHistoryAsync(string roomId, int skip, int take)
{
var messages = await _repository.GetMessagesAsync(roomId, skip, take + 1);
var hasMore = messages.Count > take;
if (hasMore)
{
messages = messages.Take(take).ToList();
}
var totalCount = await _repository.GetRoomMessageCountAsync(roomId);
return new RoomHistory
{
Messages = messages,
HasMore = hasMore,
TotalCount = totalCount
};
}
public async Task<List<ChatRoom>> GetAvailableRoomsAsync()
{
return await _repository.GetRoomsAsync();
}
public async Task<ChatRoom> CreateRoomAsync(string roomName, string createdBy)
{
var room = new ChatRoom
{
Id = Guid.NewGuid().ToString(),
Name = roomName,
CreatedBy = createdBy,
CreatedAt = DateTime.UtcNow,
IsActive = true
};
await _repository.AddRoomAsync(room);
_logger.LogInformation("Room {RoomName} created by {User}", roomName, createdBy);
return room;
}
}
4. SignalR Hubs and Groups
Advanced Group Management
public class GroupManagementHub : Hub
{
private readonly IGroupService _groupService;
private readonly ILogger<GroupManagementHub> _logger;
public GroupManagementHub(IGroupService groupService, ILogger<GroupManagementHub> logger)
{
_groupService = groupService;
_logger = logger;
}
// Join multiple groups
public async Task JoinGroups(string[] groupNames)
{
foreach (var groupName in groupNames)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
_logger.LogDebug("Connection {ConnectionId} joined group {GroupName}",
Context.ConnectionId, groupName);
}
await Clients.Caller.SendAsync("GroupsJoined", groupNames);
}
// Leave specific groups
public async Task LeaveGroups(string[] groupNames)
{
foreach (var groupName in groupNames)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
_logger.LogDebug("Connection {ConnectionId} left group {GroupName}",
Context.ConnectionId, groupName);
}
await Clients.Caller.SendAsync("GroupsLeft", groupNames);
}
// Get groups for current connection
public async Task<string[]> GetMyGroups()
{
// Note: SignalR doesn't provide a built-in way to get groups for a connection
// You need to track this yourself
return await _groupService.GetConnectionGroupsAsync(Context.ConnectionId);
}
// Send message to specific groups
public async Task SendToGroups(string[] groupNames, string message)
{
if (groupNames == null || !groupNames.Any())
return;
// Send to multiple groups
foreach (var groupName in groupNames)
{
await Clients.Group(groupName).SendAsync("ReceiveGroupMessage",
Context.ConnectionId, message, DateTime.UtcNow);
}
_logger.LogDebug("Message sent to groups: {Groups}", string.Join(", ", groupNames));
}
// Broadcast to all except specified groups
public async Task BroadcastExceptGroups(string[] excludedGroups, string message)
{
// This requires custom implementation since SignalR doesn't have built-in exclusion
var allConnections = await _groupService.GetAllConnectionsAsync();
var excludedConnections = new HashSet<string>();
foreach (var group in excludedGroups)
{
var groupConnections = await _groupService.GetGroupConnectionsAsync(group);
foreach (var connection in groupConnections)
{
excludedConnections.Add(connection);
}
}
var targetConnections = allConnections.Except(excludedConnections).ToList();
foreach (var connectionId in targetConnections)
{
await Clients.Client(connectionId).SendAsync("ReceiveMessage",
"System", message, DateTime.UtcNow);
}
}
}
// Custom group tracking service
public interface IGroupService
{
Task AddConnectionToGroupAsync(string connectionId, string groupName);
Task RemoveConnectionFromGroupAsync(string connectionId, string groupName);
Task<List<string>> GetConnectionGroupsAsync(string connectionId);
Task<List<string>> GetGroupConnectionsAsync(string groupName);
Task<List<string>> GetAllConnectionsAsync();
}
public class InMemoryGroupService : IGroupService
{
private readonly ConcurrentDictionary<string, HashSet<string>> _connectionGroups = new();
private readonly ConcurrentDictionary<string, HashSet<string>> _groupConnections = new();
public Task AddConnectionToGroupAsync(string connectionId, string groupName)
{
// Track connection -> groups
_connectionGroups.AddOrUpdate(connectionId,
new HashSet<string> { groupName },
(key, existing) =>
{
existing.Add(groupName);
return existing;
});
// Track group -> connections
_groupConnections.AddOrUpdate(groupName,
new HashSet<string> { connectionId },
(key, existing) =>
{
existing.Add(connectionId);
return existing;
});
return Task.CompletedTask;
}
public Task RemoveConnectionFromGroupAsync(string connectionId, string groupName)
{
// Remove from connection -> groups
if (_connectionGroups.TryGetValue(connectionId, out var groups))
{
groups.Remove(groupName);
if (!groups.Any())
{
_connectionGroups.TryRemove(connectionId, out _);
}
}
// Remove from group -> connections
if (_groupConnections.TryGetValue(groupName, out var connections))
{
connections.Remove(connectionId);
if (!connections.Any())
{
_groupConnections.TryRemove(groupName, out _);
}
}
return Task.CompletedTask;
}
public Task<List<string>> GetConnectionGroupsAsync(string connectionId)
{
if (_connectionGroups.TryGetValue(connectionId, out var groups))
{
return Task.FromResult(groups.ToList());
}
return Task.FromResult(new List<string>());
}
public Task<List<string>> GetGroupConnectionsAsync(string groupName)
{
if (_groupConnections.TryGetValue(groupName, out var connections))
{
return Task.FromResult(connections.ToList());
}
return Task.FromResult(new List<string>());
}
public Task<List<string>> GetAllConnectionsAsync()
{
return Task.FromResult(_connectionGroups.Keys.ToList());
}
}
Real-Time Notification System
csharp
public interface INotificationClient
{
Task ReceiveNotification(Notification notification);
Task NotificationRead(string notificationId);
Task NotificationCountUpdated(int unreadCount);
}
public class NotificationHub : Hub<INotificationClient>
{
private readonly INotificationService _notificationService;
private readonly ILogger<NotificationHub> _logger;
public NotificationHub(
INotificationService notificationService,
ILogger<NotificationHub> logger)
{
_notificationService = notificationService;
_logger = logger;
}
public async Task MarkAsRead(string notificationId)
{
var userId = GetUserIdFromContext();
if (string.IsNullOrEmpty(userId)) return;
await _notificationService.MarkAsReadAsync(notificationId, userId);
await Clients.Caller.NotificationRead(notificationId);
// Update unread count
var unreadCount = await _notificationService.GetUnreadCountAsync(userId);
await Clients.Caller.NotificationCountUpdated(unreadCount);
}
public async Task MarkAllAsRead()
{
var userId = GetUserIdFromContext();
if (string.IsNullOrEmpty(userId)) return;
await _notificationService.MarkAllAsReadAsync(userId);
await Clients.Caller.NotificationRead("all");
await Clients.Caller.NotificationCountUpdated(0);
}
public async Task<List<Notification>> GetNotifications(int skip = 0, int take = 20)
{
var userId = GetUserIdFromContext();
if (string.IsNullOrEmpty(userId)) return new List<Notification>();
return await _notificationService.GetUserNotificationsAsync(userId, skip, take);
}
public override async Task OnConnectedAsync()
{
var userId = GetUserIdFromContext();
if (!string.IsNullOrEmpty(userId))
{
await Groups.AddToGroupAsync(Context.ConnectionId, $"user_{userId}");
// Send initial unread count
var unreadCount = await _notificationService.GetUnreadCountAsync(userId);
await Clients.Caller.NotificationCountUpdated(unreadCount);
_logger.LogDebug("User {UserId} connected to notifications", userId);
}
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var userId = GetUserIdFromContext();
if (!string.IsNullOrEmpty(userId))
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user_{userId}");
}
await base.OnDisconnectedAsync(exception);
}
private string? GetUserIdFromContext()
{
// In a real application, you'd get this from the claims
return Context.User?.FindFirst("sub")?.Value;
}
}
// Notification service for sending notifications
public class NotificationService : INotificationService
{
private readonly IHubContext<NotificationHub, INotificationClient> _hubContext;
private readonly INotificationRepository _repository;
private readonly ILogger<NotificationService> _logger;
public NotificationService(
IHubContext<NotificationHub, INotificationClient> hubContext,
INotificationRepository repository,
ILogger<NotificationService> logger)
{
_hubContext = hubContext;
_repository = repository;
_logger = logger;
}
public async Task SendNotificationAsync(Notification notification)
{
await _repository.AddNotificationAsync(notification);
// Send to specific user
await _hubContext.Clients.Group($"user_{notification.UserId}")
.ReceiveNotification(notification);
_logger.LogInformation("Notification sent to user {UserId}", notification.UserId);
}
public async Task SendNotificationToUsersAsync(Notification notification, IEnumerable<string> userIds)
{
foreach (var userId in userIds)
{
var userNotification = notification with { UserId = userId, Id = Guid.NewGuid().ToString() };
await _repository.AddNotificationAsync(userNotification);
await _hubContext.Clients.Group($"user_{userId}")
.ReceiveNotification(userNotification);
}
_logger.LogInformation("Notification sent to {Count} users", userIds.Count());
}
public async Task BroadcastNotificationAsync(Notification notification)
{
// This would send to all connected users
// Be careful with this in production!
await _hubContext.Clients.All.ReceiveNotification(notification);
_logger.LogInformation("Broadcast notification sent to all users");
}
public async Task MarkAsReadAsync(string notificationId, string userId)
{
await _repository.MarkAsReadAsync(notificationId, userId);
}
public async Task MarkAllAsReadAsync(string userId)
{
await _repository.MarkAllAsReadAsync(userId);
}
public async Task<int> GetUnreadCountAsync(string userId)
{
return await _repository.GetUnreadCountAsync(userId);
}
public async Task<List<Notification>> GetUserNotificationsAsync(string userId, int skip, int take)
{
return await _repository.GetUserNotificationsAsync(userId, skip, take);
}
}
public record Notification(
string Id,
string UserId,
string Title,
string Message,
NotificationType Type,
DateTime CreatedAt,
bool IsRead = false,
string? ActionUrl = null,
Dictionary<string, object>? Data = null);
public enum NotificationType
{
Info,
Success,
Warning,
Error,
System
}
5. Scaling SignalR Applications
Redis Backplane for Scale-Out
// Program.cs configuration for Redis backplane
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR()
.AddStackExchangeRedis(redisConnectionString, options =>
{
options.Configuration.ChannelPrefix = "MyApp";
});
var app = builder.Build();
app.MapHub<ChatHub>("/chathub");
app.MapHub<NotificationHub>("/notifications");
app.Run();
Azure SignalR Service Integration
csharp
// Azure SignalR Service configuration
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR()
.AddAzureSignalR(options =>
{
options.ServerStickyMode = ServerStickyMode.Required;
options.RetryInterval = TimeSpan.FromSeconds(1);
options.MaxRetries = 3;
});
// Or using connection string from configuration
builder.Services.AddSignalR()
.AddAzureSignalR(builder.Configuration["Azure:SignalR:ConnectionString"]);
var app = builder.Build();
app.MapHub<ChatHub>("/chathub");
app.MapHub<NotificationHub>("/notifications");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapHub<NotificationHub>("/notifications");
});
app.Run();
Custom Scale-Out Implementation
csharp
public interface IMessageBus
{
Task PublishAsync<T>(string channel, T message);
Task SubscribeAsync<T>(string channel, Func<T, Task> handler);
Task UnsubscribeAsync(string channel);
}
public class RedisMessageBus : IMessageBus
{
private readonly IConnectionMultiplexer _redis;
private readonly ILogger<RedisMessageBus> _logger;
private readonly Dictionary<string, List<Func<object, Task>>> _handlers = new();
public RedisMessageBus(IConnectionMultiplexer redis, ILogger<RedisMessageBus> logger)
{
_redis = redis;
_logger = logger;
}
public async Task PublishAsync<T>(string channel, T message)
{
var subscriber = _redis.GetSubscriber();
var serialized = JsonSerializer.Serialize(message);
await subscriber.PublishAsync(channel, serialized);
_logger.LogDebug("Message published to channel {Channel}", channel);
}
public async Task SubscribeAsync<T>(string channel, Func<T, Task> handler)
{
var subscriber = _redis.GetSubscriber();
await subscriber.SubscribeAsync(channel, async (redisChannel, value) =>
{
try
{
var message = JsonSerializer.Deserialize<T>(value!);
if (message != null)
{
await handler(message);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling message from channel {Channel}", channel);
}
});
_logger.LogInformation("Subscribed to channel {Channel}", channel);
}
public async Task UnsubscribeAsync(string channel)
{
var subscriber = _redis.GetSubscriber();
await subscriber.UnsubscribeAsync(channel);
_logger.LogInformation("Unsubscribed from channel {Channel}", channel);
}
}
// Scale-out aware hub
public class ScalableChatHub : Hub
{
private readonly IMessageBus _messageBus;
private readonly ILogger<ScalableChatHub> _logger;
public ScalableChatHub(IMessageBus messageBus, ILogger<ScalableChatHub> logger)
{
_messageBus = messageBus;
_logger = logger;
}
public async Task SendMessageToRoom(string roomId, string user, string message)
{
// Store message in database
// ...
// Broadcast to local clients
await Clients.Group(roomId).ReceiveMessage(user, message, DateTime.UtcNow.ToString());
// Publish to message bus for other servers
var broadcastMessage = new BroadcastMessage
{
ServerId = GetServerId(),
RoomId = roomId,
User = user,
Message = message,
Timestamp = DateTime.UtcNow
};
await _messageBus.PublishAsync($"chat_room_{roomId}", broadcastMessage);
}
public override async Task OnConnectedAsync()
{
// Subscribe to message bus for this server
var roomId = GetRoomIdFromContext();
if (!string.IsNullOrEmpty(roomId))
{
await _messageBus.SubscribeAsync<BroadcastMessage>($"chat_room_{roomId}",
async message =>
{
// Ignore messages from this server
if (message.ServerId != GetServerId())
{
await Clients.Group(roomId).ReceiveMessage(
message.User, message.Message, message.Timestamp.ToString());
}
});
}
await base.OnConnectedAsync();
}
private string GetServerId()
{
// This could be machine name, container ID, or a configured value
return Environment.MachineName;
}
private string? GetRoomIdFromContext()
{
// Extract room ID from query string or headers
var httpContext = Context.GetHttpContext();
return httpContext?.Request.Query["roomId"].ToString();
}
}
public class BroadcastMessage
{
public string ServerId { get; set; } = string.Empty;
public string RoomId { get; set; } = string.Empty;
public string User { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public DateTime Timestamp { get; set; }
}
6. gRPC Core Concepts
Introduction to gRPC
gRPC is a modern, high-performance RPC (Remote Procedure Call) framework that can run in any environment. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as:
Bidirectional streaming
Flow control
Authentication
Cancellation and timeouts
Protocol Buffers Definition
syntax = "proto3";
import "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";
option csharp_namespace = "ECommerce.Grpc";
// Product service definition
service ProductService {
rpc GetProduct (GetProductRequest) returns (ProductResponse);
rpc GetProducts (GetProductsRequest) returns (stream ProductResponse);
rpc CreateProduct (CreateProductRequest) returns (ProductResponse);
rpc UpdateProduct (UpdateProductRequest) returns (ProductResponse);
rpc DeleteProduct (DeleteProductRequest) returns (google.protobuf.Empty);
rpc StreamProductUpdates (StreamProductUpdatesRequest) returns (stream ProductUpdate);
}
// Order service definition
service OrderService {
rpc CreateOrder (CreateOrderRequest) returns (OrderResponse);
rpc GetOrder (GetOrderRequest) returns (OrderResponse);
rpc StreamOrders (StreamOrdersRequest) returns (stream OrderResponse);
rpc ProcessOrderStream (stream OrderProcessRequest) returns (stream OrderProcessResponse);
}
// Message definitions
message GetProductRequest {
int32 product_id = 1;
}
message GetProductsRequest {
repeated int32 product_ids = 1;
string category = 2;
int32 page_size = 3;
string page_token = 4;
}
message CreateProductRequest {
string name = 1;
string description = 2;
double price = 3;
int32 stock_quantity = 4;
string category_id = 5;
}
message UpdateProductRequest {
int32 product_id = 1;
string name = 2;
string description = 3;
double price = 4;
int32 stock_quantity = 5;
}
message DeleteProductRequest {
int32 product_id = 1;
}
message ProductResponse {
int32 product_id = 1;
string name = 2;
string description = 3;
double price = 4;
int32 stock_quantity = 5;
string category_id = 6;
google.protobuf.Timestamp created_at = 7;
google.protobuf.Timestamp updated_at = 8;
}
message ProductUpdate {
int32 product_id = 1;
ProductUpdateType update_type = 2;
ProductResponse product = 3;
google.protobuf.Timestamp timestamp = 4;
}
enum ProductUpdateType {
CREATED = 0;
UPDATED = 1;
DELETED = 2;
PRICE_CHANGED = 3;
STOCK_UPDATED = 4;
}
message StreamProductUpdatesRequest {
repeated int32 product_ids = 1;
repeated string categories = 2;
}
// Order messages
message CreateOrderRequest {
int32 user_id = 1;
repeated OrderItem items = 2;
string shipping_address = 3;
}
message OrderItem {
int32 product_id = 1;
int32 quantity = 2;
double unit_price = 3;
}
message GetOrderRequest {
int32 order_id = 1;
}
message OrderResponse {
int32 order_id = 1;
int32 user_id = 2;
repeated OrderItem items = 3;
double total_amount = 4;
OrderStatus status = 5;
string shipping_address = 6;
google.protobuf.Timestamp created_at = 7;
google.protobuf.Timestamp updated_at = 8;
}
message StreamOrdersRequest {
int32 user_id = 1;
OrderStatus status = 2;
google.protobuf.Timestamp from_date = 3;
}
message OrderProcessRequest {
int32 order_id = 1;
string action = 2; // "process", "cancel", "update"
map<string, string> metadata = 3;
}
message OrderProcessResponse {
int32 order_id = 1;
bool success = 2;
string message = 3;
OrderStatus new_status = 4;
}
enum OrderStatus {
PENDING = 0;
CONFIRMED = 1;
PROCESSING = 2;
SHIPPED = 3;
DELIVERED = 4;
CANCELLED = 5;
}
gRPC Server Configuration
csharp
// Program.cs for gRPC server
using ECommerce.Grpc;
var builder = WebApplication.CreateBuilder(args);
// Add gRPC services
builder.Services.AddGrpc(options =>
{
options.EnableDetailedErrors = true;
options.Interceptors.Add<ExceptionInterceptor>();
options.Interceptors.Add<LoggingInterceptor>();
options.MaxReceiveMessageSize = 5 * 1024 * 1024; // 5MB
options.MaxSendMessageSize = 5 * 1024 * 1024; // 5MB
});
// Add gRPC reflection for testing
builder.Services.AddGrpcReflection();
// Register application services
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
// Configure the HTTP request pipeline
app.MapGrpcService<ProductGrpcService>();
app.MapGrpcService<OrderGrpcService>();
// Enable gRPC reflection in development
if (app.Environment.IsDevelopment())
{
app.MapGrpcReflectionService();
}
// Health checks for gRPC services
app.MapGet("/", () => "gRPC server is running. Use a gRPC client to communicate.");
app.Run();
// gRPC interceptors for cross-cutting concerns
public class ExceptionInterceptor : Interceptor
{
private readonly ILogger<ExceptionInterceptor> _logger;
public ExceptionInterceptor(ILogger<ExceptionInterceptor> logger)
{
_logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
try
{
return await continuation(request, context);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing gRPC call {Method}", context.Method);
throw new RpcException(new Status(StatusCode.Internal, "An error occurred"));
}
}
}
public class LoggingInterceptor : Interceptor
{
private readonly ILogger<LoggingInterceptor> _logger;
public LoggingInterceptor(ILogger<LoggingInterceptor> logger)
{
_logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation("Starting gRPC call {Method}", context.Method);
try
{
var response = await continuation(request, context);
stopwatch.Stop();
_logger.LogInformation(
"Completed gRPC call {Method} in {ElapsedMs}ms",
context.Method, stopwatch.ElapsedMilliseconds);
return response;
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(
ex, "gRPC call {Method} failed after {ElapsedMs}ms",
context.Method, stopwatch.ElapsedMilliseconds);
throw;
}
}
}
7. Building High-Performance gRPC Services
Product gRPC Service Implementation
using Grpc.Core;
using Google.Protobuf.WellKnownTypes;
using ECommerce.Grpc;
namespace ECommerce.Server.Services;
public class ProductGrpcService : ProductService.ProductServiceBase
{
private readonly IProductService _productService;
private readonly ILogger<ProductGrpcService> _logger;
public ProductGrpcService(
IProductService productService,
ILogger<ProductGrpcService> logger)
{
_productService = productService;
_logger = logger;
}
public override async Task<ProductResponse> GetProduct(
GetProductRequest request,
ServerCallContext context)
{
_logger.LogInformation("Getting product {ProductId}", request.ProductId);
var product = await _productService.GetProductAsync(request.ProductId);
if (product == null)
{
throw new RpcException(
new Status(StatusCode.NotFound, $"Product {request.ProductId} not found"));
}
return MapToProductResponse(product);
}
public override async Task GetProducts(
GetProductsRequest request,
IServerStreamWriter<ProductResponse> responseStream,
ServerCallContext context)
{
_logger.LogInformation("Streaming products for request");
var products = await _productService.GetProductsAsync(
request.ProductIds.ToList(),
request.Category,
request.PageSize,
request.PageToken);
foreach (var product in products)
{
// Check if the client has cancelled the request
if (context.CancellationToken.IsCancellationRequested)
{
_logger.LogInformation("Client cancelled product stream");
break;
}
await responseStream.WriteAsync(MapToProductResponse(product));
// Small delay to demonstrate streaming
await Task.Delay(100, context.CancellationToken);
}
_logger.LogInformation("Completed streaming products");
}
public override async Task<ProductResponse> CreateProduct(
CreateProductRequest request,
ServerCallContext context)
{
_logger.LogInformation("Creating new product: {ProductName}", request.Name);
var product = new Product
{
Name = request.Name,
Description = request.Description,
Price = (decimal)request.Price,
StockQuantity = request.StockQuantity,
CategoryId = request.CategoryId
};
var createdProduct = await _productService.CreateProductAsync(product);
return MapToProductResponse(createdProduct);
}
public override async Task<ProductResponse> UpdateProduct(
UpdateProductRequest request,
ServerCallContext context)
{
_logger.LogInformation("Updating product {ProductId}", request.ProductId);
var product = await _productService.GetProductAsync(request.ProductId);
if (product == null)
{
throw new RpcException(
new Status(StatusCode.NotFound, $"Product {request.ProductId} not found"));
}
product.Name = request.Name;
product.Description = request.Description;
product.Price = (decimal)request.Price;
product.StockQuantity = request.StockQuantity;
var updatedProduct = await _productService.UpdateProductAsync(product);
return MapToProductResponse(updatedProduct);
}
public override async Task<Empty> DeleteProduct(
DeleteProductRequest request,
ServerCallContext context)
{
_logger.LogInformation("Deleting product {ProductId}", request.ProductId);
var success = await _productService.DeleteProductAsync(request.ProductId);
if (!success)
{
throw new RpcException(
new Status(StatusCode.NotFound, $"Product {request.ProductId} not found"));
}
return new Empty();
}
public override async Task StreamProductUpdates(
StreamProductUpdatesRequest request,
IServerStreamWriter<ProductUpdate> responseStream,
ServerCallContext context)
{
_logger.LogInformation("Starting product updates stream");
// Subscribe to product updates
var cancellationToken = context.CancellationToken;
var productIds = request.ProductIds.ToList();
var categories = request.Categories.ToList();
// This would typically connect to a message bus or database change feed
var productUpdateChannel = _productService.GetProductUpdateChannel(
productIds, categories, cancellationToken);
try
{
await foreach (var update in productUpdateChannel.ReadAllAsync(cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
break;
var productUpdate = new ProductUpdate
{
ProductId = update.ProductId,
UpdateType = MapToUpdateType(update.UpdateType),
Product = MapToProductResponse(update.Product),
Timestamp = Timestamp.FromDateTime(update.Timestamp)
};
await responseStream.WriteAsync(productUpdate);
}
}
catch (OperationCanceledException)
{
_logger.LogInformation("Product updates stream cancelled by client");
}
_logger.LogInformation("Product updates stream completed");
}
private static ProductResponse MapToProductResponse(Product product)
{
return new ProductResponse
{
ProductId = product.Id,
Name = product.Name,
Description = product.Description,
Price = (double)product.Price,
StockQuantity = product.StockQuantity,
CategoryId = product.CategoryId,
CreatedAt = Timestamp.FromDateTime(product.CreatedAt),
UpdatedAt = Timestamp.FromDateTime(product.UpdatedAt)
};
}
private static ProductUpdateType MapToUpdateType(ProductUpdateTypeEnum updateType)
{
return updateType switch
{
ProductUpdateTypeEnum.Created => ProductUpdateType.Created,
ProductUpdateTypeEnum.Updated => ProductUpdateType.Updated,
ProductUpdateTypeEnum.Deleted => ProductUpdateType.Deleted,
ProductUpdateTypeEnum.PriceChanged => ProductUpdateType.PriceChanged,
ProductUpdateTypeEnum.StockUpdated => ProductUpdateType.StockUpdated,
_ => ProductUpdateType.Updated
};
}
}
// Supporting classes
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
public int StockQuantity { get; set; }
public string CategoryId { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public class ProductUpdateEvent
{
public int ProductId { get; set; }
public ProductUpdateTypeEnum UpdateType { get; set; }
public Product Product { get; set; } = null!;
public DateTime Timestamp { get; set; }
}
public enum ProductUpdateTypeEnum
{
Created,
Updated,
Deleted,
PriceChanged,
StockUpdated
}

Join the conversation! Your thoughts help the community grow.