LESSON 6 OF 14

6. Building a Real-Time Notification Center

Persist notifications in a database, broadcast them with SignalR, and build a JavaScript notification panel with an unread counter.

45 dk 57

Introduction

In the previous lesson, we worked with user-based and group-based messaging. This lesson moves that communication model into a more realistic application scenario: a persistent notification center. The goal is not merely to send a message to currently connected clients. Notifications should be stored in a database, displayed later when the user opens the panel, tracked as read or unread, and synchronized immediately across every open client.

Our notification will contain a recipient user, title, message, optional target URL, creation time, and read state. An HTTP API will provide the initial list and pagination flow. SignalR will broadcast notification-created, notification-read, and mark-all-as-read events in real time.

This distinction is important: SignalR is a temporary communication channel, while the database is the persistent source of truth. A notification sent while the user is disconnected may not be received through SignalR, but it can still be retrieved later through the API.

Architecture and data model

Because notifications belong to a specific user, the broadcast target will be Clients.User(userId). By default, SignalR derives the user identifier from ClaimTypes.NameIdentifier. Make sure the corresponding claim in the JWT is unique. If the same user connects from multiple browsers or devices, a message sent to that user reaches all of those connections.

An example entity and DTO model looks like this:

public sealed class Notification
{
    public long Id { get; set; }
    public string UserId { get; set; } = null!;
    public string Title { get; set; } = null!;
    public string Message { get; set; } = null!;
    public string? TargetUrl { get; set; }
    public bool IsRead { get; set; }
    public DateTime CreatedAtUtc { get; set; }
    public string? DeduplicationKey { get; set; }
}

public sealed record NotificationDto(
    long Id,
    string Title,
    string Message,
    string? TargetUrl,
    bool IsRead,
    DateTime CreatedAtUtc);

The DeduplicationKey helps prevent the same business event from producing duplicate notifications. For example, an order approval may use order:123:approved. In production, consider a unique database constraint over the user and key.

Preparing the SignalR hub

Only authenticated users should be able to connect to the hub. Do not accept the user ID as a client-supplied argument in hub methods. Always derive it from the authenticated connection's Context.UserIdentifier.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

[Authorize]
public sealed class NotificationHub : Hub
{
    private readonly INotificationService _notifications;

    public NotificationHub(INotificationService notifications)
    {
        _notifications = notifications;
    }

    public async Task MarkAsRead(long notificationId)
    {
        var userId = Context.UserIdentifier
            ?? throw new HubException("The user identifier is missing.");

        await _notifications.MarkAsReadAsync(userId, notificationId,
            Context.ConnectionAborted);
    }

    public async Task MarkAllAsRead()
    {
        var userId = Context.UserIdentifier
            ?? throw new HubException("The user identifier is missing.");

        await _notifications.MarkAllAsReadAsync(userId,
            Context.ConnectionAborted);
    }
}

The hub should not become a direct database-access layer. Move business logic into a service so the same operations can be tested and reused by an HTTP controller, a background service, or another application component.

Persistence and broadcasting

When a notification is created, save it to the database first and then publish the resulting record through SignalR. If broadcasting fails, the persistent record should not disappear. Therefore, do not treat the database operation and real-time broadcast as if they were one transaction. For systems that require stronger delivery guarantees, an outbox pattern is appropriate; here we will implement the basic flow.

public interface INotificationService
{
    Task<NotificationDto> CreateAsync(
        string userId, string title, string message,
        string? targetUrl, string? deduplicationKey,
        CancellationToken cancellationToken);

    Task<IReadOnlyList<NotificationDto>> GetForUserAsync(
        string userId, int page, int pageSize,
        CancellationToken cancellationToken);

    Task MarkAsReadAsync(string userId, long id,
        CancellationToken cancellationToken);

    Task MarkAllAsReadAsync(string userId,
        CancellationToken cancellationToken);
}
public sealed class NotificationService : INotificationService
{
    private readonly AppDbContext _db;
    private readonly IHubContext<NotificationHub> _hub;

    public NotificationService(AppDbContext db,
        IHubContext<NotificationHub> hub)
    {
        _db = db;
        _hub = hub;
    }

    public async Task<NotificationDto> CreateAsync(
        string userId, string title, string message,
        string? targetUrl, string? deduplicationKey,
        CancellationToken cancellationToken)
    {
        if (!string.IsNullOrWhiteSpace(deduplicationKey))
        {
            var existing = await _db.Notifications.SingleOrDefaultAsync(
                x => x.UserId == userId &&
                     x.DeduplicationKey == deduplicationKey,
                cancellationToken);

            if (existing is not null)
                return ToDto(existing);
        }

        var entity = new Notification
        {
            UserId = userId,
            Title = title,
            Message = message,
            TargetUrl = targetUrl,
            DeduplicationKey = deduplicationKey,
            CreatedAtUtc = DateTime.UtcNow
        };

        _db.Notifications.Add(entity);
        await _db.SaveChangesAsync(cancellationToken);

        var dto = ToDto(entity);
        await _hub.Clients.User(userId)
            .SendAsync("notificationCreated", dto, cancellationToken);

        return dto;
    }

    public async Task MarkAsReadAsync(string userId, long id,
        CancellationToken cancellationToken)
    {
        var notification = await _db.Notifications.SingleOrDefaultAsync(
            x => x.Id == id && x.UserId == userId,
            cancellationToken);

        if (notification is null)
            return;

        if (!notification.IsRead)
        {
            notification.IsRead = true;
            await _db.SaveChangesAsync(cancellationToken);
        }

        await _hub.Clients.User(userId).SendAsync(
            "notificationRead",
            new { notificationId = id },
            cancellationToken);
    }

    public async Task MarkAllAsReadAsync(string userId,
        CancellationToken cancellationToken)
    {
        await _db.Notifications
            .Where(x => x.UserId == userId && !x.IsRead)
            .ExecuteUpdateAsync(s => s.SetProperty(x => x.IsRead, true),
                cancellationToken);

        await _hub.Clients.User(userId).SendAsync(
            "notificationsAllRead", cancellationToken);
    }

    public async Task<IReadOnlyList<NotificationDto>> GetForUserAsync(
        string userId, int page, int pageSize,
        CancellationToken cancellationToken)
    {
        page = Math.Max(page, 1);
        pageSize = Math.Clamp(pageSize, 1, 50);

        return await _db.Notifications
            .Where(x => x.UserId == userId)
            .OrderByDescending(x => x.CreatedAtUtc)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(x => new NotificationDto(
                x.Id, x.Title, x.Message, x.TargetUrl,
                x.IsRead, x.CreatedAtUtc))
            .ToListAsync(cancellationToken);
    }

    private static NotificationDto ToDto(Notification x) =>
        new(x.Id, x.Title, x.Message, x.TargetUrl,
            x.IsRead, x.CreatedAtUtc);
}

When a request is repeated, returning an existing record is not enough by itself; ensure that the existing record is not broadcast a second time. If two parallel requests can use the same key, add a database uniqueness constraint and handle the resulting conflict safely.

Listing API and configuration

Load the notification history through an API when the panel is initialized. The endpoint should not accept the user ID from a route or query string. The identity must come from the JWT.

[ApiController]
[Route("api/notifications")]
[Authorize]
public sealed class NotificationsController : ControllerBase
{
    private readonly INotificationService _service;

    public NotificationsController(INotificationService service)
        => _service = service;

    [HttpGet]
    public async Task<IActionResult> Get(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken cancellationToken = default)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (userId is null)
            return Unauthorized();

        var result = await _service.GetForUserAsync(
            userId, page, pageSize, cancellationToken);
        return Ok(result);
    }
}
builder.Services.AddSignalR();
builder.Services.AddScoped<INotificationService, NotificationService>();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapHub<NotificationHub>("/hubs/notifications");

When JWT authentication is used, provide the token through accessTokenFactory in the JavaScript client. Mapping the hub after the authentication and authorization middleware keeps it aligned with the application's general security pipeline.

Building the JavaScript notification panel

The client combines two data flows: the initial list loaded over HTTP and live events received through SignalR. Prevent duplicates by checking the notification ID before adding an item to the DOM.

const notificationState = {
    items: new Map(),
    connection: null
};

function renderNotification(notification) {
    if (notificationState.items.has(notification.id)) return;

    notificationState.items.set(notification.id, notification);

    const item = document.createElement("div");
    item.dataset.notificationId = notification.id;
    item.className = notification.isRead
        ? "notification read"
        : "notification unread";
    item.textContent = `${notification.title}: ${notification.message}`;

    document.querySelector("#notificationList")
        .prepend(item);
    updateUnreadCount();
}

function updateUnreadCount() {
    const unread = [...notificationState.items.values()]
        .filter(x => !x.isRead).length;
    document.querySelector("#notificationCount")
        .textContent = String(unread);
}

async function loadNotifications() {
    const response = await fetch("/api/notifications?page=1&pageSize=20");
    if (!response.ok) throw new Error("Notifications could not be loaded.");

    const notifications = await response.json();
    notifications.reverse().forEach(renderNotification);
}

async function startNotifications() {
    notificationState.connection = new signalR.HubConnectionBuilder()
        .withUrl("/hubs/notifications", {
            accessTokenFactory: () => localStorage.getItem("access_token")
        })
        .withAutomaticReconnect()
        .build();

    notificationState.connection.on("notificationCreated", notification => {
        renderNotification(notification);
    });

    notificationState.connection.on("notificationRead", ({ notificationId }) => {
        const item = notificationState.items.get(notificationId);
        if (item) {
            item.isRead = true;
            updateUnreadCount();
        }
    });

    notificationState.connection.on("notificationsAllRead", () => {
        notificationState.items.forEach(item => item.isRead = true);
        updateUnreadCount();
    });

    await notificationState.connection.start();
}

async function markAsRead(notificationId) {
    await notificationState.connection.invoke(
        "MarkAsRead", notificationId);
}

async function markAllAsRead() {
    await notificationState.connection.invoke("MarkAllAsRead");
}

await loadNotifications();
await startNotifications();

In a real application, loading the history first and connecting afterward can create a small gap in which a notification is missed. A safer approach is to start the connection, then load the list and merge both streams by notification ID. Even if HTTP and SignalR return the same record, the Map prevents a duplicate.

Common mistakes and security checks

  • Accepting the user ID from the client: Never trust a userId supplied by JavaScript or the request body. Resolve it from the authenticated JWT claim.
  • Exposing another user's notifications: Add Notification.UserId == currentUserId to every query and protect both the controller and hub with [Authorize].
  • Duplicate notifications: Use an idempotency key for retried HTTP requests or background-service retries. Also deduplicate by notification ID in the client.
  • Losing data while disconnected: Do not treat SignalR delivery as persistence. Synchronize from the API when the panel opens or reconnects.
  • Changing read state only in the browser: The counter may update immediately, but the server must persist the read state.
  • Ignoring failures: Wrap invoke calls in try/catch. If the connection is unavailable, provide a retry or refresh action.
  • HTML injection: Use textContent instead of innerHTML for notification text, or apply a trusted sanitization layer.

Practice exercise

Complete the following small application:

  1. Create the Notifications table and an EF Core migration.
  2. Implement a listing endpoint that returns only the authenticated user's notifications.
  3. Generate a notification from a test endpoint or an existing business workflow using a DeduplicationKey.
  4. Add an unread counter, a mark-one-as-read action, and a mark-all-as-read action to the panel.
  5. Open two browser tabs using the same JWT. Verify that new-notification and read-state events appear in both tabs.
  6. Send two requests with the same idempotency key. Confirm that the database contains one record and the client displays one notification.
  7. Try the API and hub without a token. Verify the expected 401 response or rejected connection.
  8. Close one tab, create a notification, and reopen the tab. Confirm that the HTTP listing restores the missed notification.

Conclusion

In this lesson, we combined SignalR with a persistent notification model. The database preserves notification history and read state, while IHubContext broadcasts user-specific real-time events. On the JavaScript side, we implemented initial HTTP loading, live SignalR updates, duplicate prevention, and unread-counter management.

Next, this service can be triggered from a background service, strengthened with an outbox pattern, and extended with a Redis backplane so notification events reach every node in a multi-server deployment.

Sources