Skip to content

Advanced ​

This page covers production-level topics: retry policies, scheduling, observability, multi-tenancy, database schema, migrations, and testing strategies.

Retry Policies ​

The default in-memory queue processor retries failed notification sends with a bounded delay. The registered PollyNotificationRetryPolicy is not used by this queue path.

Configuration ​

csharp
builder.Services.AddGrydNotifications(options =>
{
    options.Retry.MaxRetries = 3;
    options.Retry.BackoffType = BackoffType.Exponential;
    options.Retry.BaseDelay = TimeSpan.FromSeconds(5);
    options.Retry.MaxDelay = TimeSpan.FromMinutes(5);
    options.Retry.UseJitter = true;
    options.Retry.NonRetryableReasons = new HashSet<DeliveryFailureReason>
    {
        DeliveryFailureReason.InvalidRecipient,
        DeliveryFailureReason.InvalidTemplate,
        DeliveryFailureReason.AuthenticationFailed
    };
});

Backoff Types ​

TypeFormulaExample (BaseDelay = 5s)
FixedBaseDelay5s, 5s, 5s
LinearBaseDelay × attempt5s, 10s, 15s
ExponentialBaseDelay × 2^(failureCount-1)5s, 10s, 20s

The first retry waits BaseDelay. UseJitter varies that delay by up to 25% in either direction. The final delay is capped at MaxDelay, including after jitter. MaxDelay cannot exceed the Task.Delay limit of 4,294,967,294 milliseconds.

The attempt budget comes from SendNotificationCommand.MaxRetries, copied to the notification entity; it defaults to 3. RetryCount counts failed sends and HasRetriesRemaining is RetryCount < MaxRetries, so a budget of 3 allows three total sends. A budget of 0 or 1 allows only the initial send. Retry.MaxRetries is retained in configuration for the unused Polly policy; the default queue processor does not use it to override an entity's budget.

Retry Flow ​

Send Attempt 1 ──► Failure
       │
       ▼
  Persist status Queued, then wait BaseDelay (with jitter)
       │
       ▼
Send Attempt 2 ──► Failure
       │
       ▼
  Persist status Queued, then wait BaseDelay × 2 (with jitter)
       │
       ▼
Send Attempt 3 ──► Failure (transient)
       │
       ▼
  Budget exhausted or reason is permanent → DeadLettered
  Last error and delivery-attempt history remain on the notification

Non-Retryable Reasons ​

If a failure reason matches NonRetryableReasons, the processor marks the notification DeadLettered without waiting or retrying. The current ChannelNotificationSender records DeliveryFailureReason.Unknown for provider failures and caught provider exceptions; providers do not yet return structured failure reasons to this path. Add Unknown to the non-retryable set only if all unclassified failures should be terminal.

Dead Letters ​

Notifications that exhaust all retry attempts are moved to a dead-letter state:

csharp
// Query dead-lettered notifications for investigation
var deadLetters = await _mediator.Send(new GetNotificationsPagedQuery
{
    Status = NotificationStatus.DeadLettered,
    Page = 1,
    PageSize = 50
}, ct);

Failed is the state written after an individual failed send. A retryable record moves back to Queued; exhausted and permanent failures end in DeadLettered.

Backoff runs inside a bounded queue-processing slot. A notification occupies one of the configured MaxConcurrency slots for the full wait, so long delays reduce batch throughput. The processor also waits for every item in the current batch before it dequeues the next batch, so a retry delay can hold up later batches even when another slot is idle. The delay observes the worker stopping token. Shutdown during backoff leaves the persisted status Queued but does not publish an in-memory queue entry. The volatile queue has no restart recovery scan; enable durable delivery from the start for persisted outbox recovery. A user cancellation during backoff is not overwritten by another processor update, and a later dequeue checks the current status before send.

Queue Processing ​

The background queue processes notifications asynchronously when EnableQueue = true:

csharp
options.Queue.BatchSize = 10;          // Notifications per batch
options.Queue.PollingInterval = 
    TimeSpan.FromSeconds(5);           // Poll frequency
options.Queue.MaxConcurrency = 4;      // Parallel senders
options.Queue.MessageExpiration = null; // No expiration by default

Queue Architecture ​

Producer (API/Command)
       │
       ▼
┌─────────────────┐
│  Queue Storage   │  (in-memory Channel<T> — default)
│  (pending msgs)  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Queue Processor │  (BackgroundService)
│  4 workers       │────► Email Sender
│  10 per batch    │────► Push Sender
│  5s polling      │────► InApp Sender
└─────────────────┘

Scheduling Notifications ​

Send Later ​

Schedule a notification for future delivery:

csharp
await _mediator.Send(new ScheduleNotificationCommand
{
    Channel = NotificationChannel.Email,
    Recipients = new[] { "user@example.com" },
    Subject = "Your trial expires tomorrow",
    TemplateId = trialExpiryTemplateId,
    Variables = new Dictionary<string, object>
    {
        ["user_name"] = "John",
        ["expiry_date"] = DateTime.UtcNow.AddDays(1)
    },
    ScheduledAt = DateTime.UtcNow.AddDays(6) // Send 1 day before trial ends
}, ct);

Cancel a Scheduled Notification ​

csharp
await _mediator.Send(new CancelScheduledNotificationCommand
{
    NotificationId = notificationId
}, ct);

Integration with GrydJobs ​

For complex scheduling (recurring reminders, cron expressions), integrate with the GrydJobs module:

csharp
// Register via GrydNotifications.Scheduling package
builder.Services.AddGrydNotifications(options => { /* ... */ })
    .AddSchedulingIntegration();
csharp
// Recurring weekly digest
await _mediator.Send(new CreateRecurringNotificationJobCommand
{
    JobName = "weekly-digest",
    CronExpression = "0 9 * * MON", // Every Monday at 9 AM
    Channel = NotificationChannel.Email,
    TemplateId = weeklyDigestTemplateId,
    RecipientQuery = "active-subscribers" // Named query
}, ct);

Observability ​

OpenTelemetry Integration ​

GrydNotifications emits traces and metrics via Gryd.Observability.OpenTelemetry:

csharp
using Gryd.Observability.Abstractions;
using Gryd.Observability.OpenTelemetry.Extensions;

builder.Services.AddGrydOpenTelemetry(new ObservabilityOptions
{
    ServiceName = "notifications-api",
    ServiceVersion = "1.0.0",
    OpenTelemetry = new OpenTelemetryOptions
    {
        Enabled = true,
        Exporter = "console"
    }
});

AddGrydNotificationsInfrastructure supplies the default Core activity source and metrics collector without replacing host registrations. It does not configure an OpenTelemetry exporter; register AddGrydOpenTelemetry separately to export those observations.

Metrics ​

MetricTypeDescription
gryd.notifications.send.attemptsCounterProvider calls, including failed and canceled calls
gryd.notifications.send.duration_msHistogram, msTime spent inside the provider call
gryd.notifications.template.rendersCounterScriban template render outcomes
gryd.notifications.template.render.duration_msHistogram, msTemplate lookup and render time

Send metrics use bounded channel, outcome and reason tags. Template metrics use only the bounded outcome tag. The channel values are email, push, in_app and unknown; undefined enum values map to unknown. No recipient, payload, template slug, provider name or exception text is exported. Provider spans may include the notification ID; metric labels never include IDs.

Metrics use the Core observability meter named from Observability:ServiceName (default gryd-service). Traces use the actual IActivitySourceProvider.Source.Name. Subscribe to those identities through Gryd.Observability.OpenTelemetry:

csharp
builder.Services.AddGrydOpenTelemetry(builder.Configuration);

Traces ​

notifications.provider.send is a client span around each actual provider call, and notifications.template.render is an internal span around Scriban template lookup and rendering. Durable queue acceptance and operation replay do not create provider send spans. Skipped work and refusals before a provider call are not counted as sends. Persistence and retry backoff are outside the provider duration. A durable sender success means the provider accepted the call. For local in-app delivery, the processor commits inbox effects, a delivery receipt and outbox completion together. For external email and push, it records outbox completion after provider acceptance; those calls do not create a local delivery receipt.

Telemetry is an operational observation, not a durable delivery ledger. Queue depth and end-to-end delivery metrics are unavailable because no global sampler emits them.

Health Checks ​

AddGrydNotificationsHealthChecks reads the optional notification queue depth. Depth above 10,000 or a queue read failure uses the configured failure status; with no queue, the check reports Healthy because no depth was available. The default failure status is Degraded (HTTP 200); choose Unhealthy for HTTP 503. Default tags omit ready, so the host must supply that tag when registering the check selected by a readiness predicate. The check does not probe SMTP, SignalR, database connectivity or schema, or worker liveness. See Health Checks configuration for the working readiness registration and endpoint example.

Multi-Tenancy ​

GrydNotifications is multi-tenancy aware through the tenant of the session (ITenantSession).

Tenant Isolation ​

Commands and queries carry no tenant (ADR 0011, D23); the handler takes it from the session, and a session without a tenant works on global data:

csharp
await _mediator.Send(new SendNotificationCommand
{
    Channel = NotificationChannel.Email,
    Recipients = new[] { "user@example.com" },
    Subject = "Welcome!"
}, ct);

When the session has a tenant:

  • Notifications are scoped to the tenant
  • Templates fall back: tenant-specific → global
  • SignalR groups include tenant: tenant_{tenantId}
  • Queries only return tenant-scoped data

Template Tenant Fallback ​

Lookup: (key="welcome", locale="pt-BR", tenantId="abc")
  1. key="welcome", locale="pt-BR", tenantId="abc"    ← Tenant + locale
  2. key="welcome", locale="pt",    tenantId="abc"    ← Tenant + language
  3. key="welcome", locale="pt-BR", tenantId=null     ← Global + locale
  4. key="welcome", locale="pt",    tenantId=null     ← Global + language
  5. key="welcome", locale=null,    tenantId=null     ← Default fallback

Per-Tenant Provider Configuration ​

Override email/push settings per tenant:

csharp
// In a custom ITenantNotificationConfigProvider
public class TenantNotificationConfig : ITenantNotificationConfigProvider
{
    public Task<EmailOptions?> GetEmailOptionsAsync(Guid tenantId, CancellationToken ct)
    {
        // Load from database, cache, etc.
        return Task.FromResult(new EmailOptions
        {
            DefaultFrom = "noreply@tenant-domain.com",
            SmtpHost = "smtp.tenant-provider.com"
        });
    }
}

Database Schema ​

All tables live in the notifications schema:

sql
-- Core tables
notifications.notifications          -- Main notification records
notifications.notification_recipients -- Per-recipient tracking
notifications.notification_templates  -- Scriban templates
notifications.notification_queue      -- Async queue (if enabled)

-- In-App tables
notifications.user_notifications     -- Per-user in-app notifications
notifications.user_devices           -- Push notification device tokens

Key Indexes ​

TableIndexPurpose
notificationsix_notifications_statusQueue processing
notificationsix_notifications_tenant_createdTenant + date queries
user_notificationsix_user_notifications_user_unreadUnread count badge
user_notificationsix_user_notifications_collapse_keyCollapse key lookup
notification_templatesix_templates_key_locale_tenantTemplate resolution

Migrations ​

Apply on Startup ​

csharp
var app = builder.Build();
await app.ApplyGrydNotificationsMigrationsAsync();

Generate SQL Script ​

bash
dotnet ef migrations script \
  --project src/Modules/Notifications/GrydNotifications.Infrastructure \
  --context NotificationsDbContext \
  --output migrations.sql

Add a New Migration ​

bash
dotnet ef migrations add AddCustomColumn \
  --project src/Modules/Notifications/GrydNotifications.Infrastructure \
  --startup-project src/Core/Gryd.API \
  --context NotificationsDbContext

Testing ​

Unit Testing Handlers ​

csharp
using NSubstitute;
using Xunit;

public class SendEmailNotificationHandlerTests
{
    private readonly IEmailSender _emailSender = Substitute.For<IEmailSender>();
    private readonly INotificationRepository _repo = Substitute.For<INotificationRepository>();
    private readonly SendEmailNotificationHandler _sut;

    public SendEmailNotificationHandlerTests()
    {
        _sut = new SendEmailNotificationHandler(_emailSender, _repo);
    }

    [Fact]
    public async Task Handle_ValidEmail_SendsAndPersists()
    {
        // Arrange
        var command = new SendEmailNotificationCommand
        {
            Recipients = new[] { "test@example.com" },
            Subject = "Test",
            Body = "<p>Hello</p>"
        };

        _emailSender.SendAsync(Arg.Any<EmailMessage>(), Arg.Any<CancellationToken>())
            .Returns(Result.Success());

        // Act
        var result = await _sut.Handle(command, CancellationToken.None);

        // Assert
        Assert.True(result.IsSuccess);
        await _emailSender.Received(1).SendAsync(
            Arg.Is<EmailMessage>(m => m.To.Contains("test@example.com")),
            Arg.Any<CancellationToken>());
        await _repo.Received(1).AddAsync(
            Arg.Any<Notification>(),
            Arg.Any<CancellationToken>());
    }
}

Testing Controllers ​

csharp
using MediatR;
using NSubstitute;
using Microsoft.AspNetCore.Mvc;

public class NotificationsControllerTests
{
    private readonly IMediator _mediator = Substitute.For<IMediator>();
    private readonly ILogger<NotificationsController> _logger = Substitute.For<ILogger<NotificationsController>>();
    private readonly NotificationsController _sut;

    public NotificationsControllerTests()
    {
        _sut = new NotificationsController(_mediator, _logger);
    }

    [Fact]
    public async Task Send_ValidRequest_ReturnsOk()
    {
        // Arrange
        var request = new SendNotificationRequest { /* ... */ };
        _mediator.Send(Arg.Any<SendNotificationCommand>(), Arg.Any<CancellationToken>())
            .Returns(Result<Guid>.Success(Guid.NewGuid()));

        // Act
        var result = await _sut.Send(request, CancellationToken.None);

        // Assert
        Assert.IsType<OkObjectResult>(result);
    }
}

Integration Tests with TestContainers ​

csharp
using Testcontainers.PostgreSql;

public class NotificationsIntegrationTests : IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .Build();

    public async Task InitializeAsync()
    {
        await _postgres.StartAsync();
        // Apply migrations
    }

    public async Task DisposeAsync() => await _postgres.DisposeAsync();

    [Fact]
    public async Task FullNotificationLifecycle_SendAndRead()
    {
        // Create factory with real database
        var factory = new WebApplicationFactory<Program>()
            .WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    services.AddGrydNotifications(options =>
                    {
                        options.ConnectionString = _postgres.GetConnectionString();
                        options.InApp.Enabled = true;
                    });
                });
            });

        var client = factory.CreateClient();

        // Send notification
        var response = await client.PostAsJsonAsync("/api/v1/notifications/send", new
        {
            channel = "InApp",
            userId = Guid.NewGuid(),
            title = "Test",
            body = "Integration test"
        });

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
    }
}

Testing SignalR Hub ​

csharp
[Fact]
public async Task NotificationHub_ReceivesRealTimeNotification()
{
    var factory = new WebApplicationFactory<Program>();
    var server = factory.Server;

    var connection = new HubConnectionBuilder()
        .WithUrl(
            $"{server.BaseAddress}hubs/notifications",
            options => options.HttpMessageHandlerFactory = _ => server.CreateHandler())
        .Build();

    var received = new TaskCompletionSource<UserNotificationDto>();
    connection.On<UserNotificationDto>("ReceiveNotification", n =>
    {
        received.SetResult(n);
    });

    await connection.StartAsync();

    // Trigger notification via API
    var client = factory.CreateClient();
    await client.PostAsJsonAsync("/api/v1/notifications/send", new { /* ... */ });

    // Wait for real-time delivery
    var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(5));
    Assert.Equal("Test", notification.Title);
}

Performance Tips ​

TipDescription
Batch emailsUse BulkBatchSize and BulkDelayBetweenBatches for mass emails
Enable queueProcess notifications asynchronously to avoid blocking API requests
Use collapse keysPrevent notification spam for repetitive events
Set expirationDefaultTimeToLive avoids stale in-app notifications
Redis backplaneRequired for SignalR with multiple server instances
Template cachingTemplates are cached by default — avoid disabling in production
Tune concurrencyAdjust Queue.MaxConcurrency based on provider rate limits
Monitor queue depthAlert on gryd.notifications.queue.depth growing continuously

Released under the MIT License.