Skip to content

Configuration ​

For the standard host setup, use the configuration facade. It binds the GrydNotifications section and resolves the database connection through its documented fallback keys:

csharp
using GrydNotifications;

builder.Services.AddGrydNotifications(builder.Configuration);

The options callback overload is also available for explicit configuration. It does not read the configuration section or resolve the facade's connection-string fallbacks, so set storage options directly when using it:

csharp
builder.Services.AddGrydNotifications(options =>
{
    options.UsePostgreSqlStorage(builder.Configuration.GetConnectionString("GrydNotifications")!);
    // Configure other options here.
});

GrydNotificationsOptions ​

Connection String ​

Required. PostgreSQL connection string for notification persistence and template storage.

csharp
options.UsePostgreSqlStorage("Host=localhost;Database=gryd_notifications;...");
// or
options.ConnectionString = "Host=localhost;Database=gryd_notifications;...";

Feature Toggles ​

PropertyTypeDefaultDescription
EnableTemplatesbooltrueEnables Scriban template engine
EnableQueuebooltrueEnables async queue processing. When false, sends synchronously
PersistNotificationsbooltruePersists notifications in the database for auditing
NotificationRetentionDaysint90Days to retain sent/failed notifications before cleanup
csharp
options.EnableTemplates = true;
options.EnableQueue = true;
options.PersistNotifications = true;
options.NotificationRetentionDays = 90;

Email Options ​

Configure email sending via SMTP (MailKit). When SmtpHost is empty the module registers a failure-returning fallback; it does not report a successful send. SmtpUseSsl=true selects STARTTLS on the configured port.

csharp
options.Email.DefaultFrom = "noreply@myapp.com";
options.Email.DefaultFromName = "My Application";
options.Email.SmtpHost = "smtp.myapp.com";
options.Email.SmtpPort = 587;
options.Email.SmtpUseSsl = true;
options.Email.SmtpUsername = "<smtp username>";
options.Email.SmtpPassword = configuration["Smtp:Password"]!;

Properties ​

PropertyTypeDefaultDescription
DefaultFromstring""Default sender email address
DefaultFromNamestring?nullDefault sender display name
SmtpHoststring?nullSMTP server hostname
SmtpPortint587SMTP server port
SmtpUseSslbooltrueUse STARTTLS (SecureSocketOptions.StartTls)
SmtpUsernamestring?nullSMTP authentication username
SmtpPasswordstring?nullSMTP authentication password
MaxAttachmentSizeMbint10Maximum attachment size per email (MB), checked when the file is attached
MaxAttachmentsPerEmailint5Maximum number of attachments per email
MaxRecipientsPerEmailint50Maximum recipients (To + Cc + Bcc)
BulkBatchSizeint100Emails per batch in bulk operations
BulkDelayBetweenBatchesTimeSpan1sRate limiting delay between batches

Using SendGrid instead of SMTP ​

To use SendGrid's HTTP API instead of SMTP, install GrydNotifications.Infrastructure.SendGrid and register its provider after AddGrydNotifications:

csharp
// Install: dotnet add package GrydNotifications.Infrastructure.SendGrid
using GrydNotifications.Infrastructure.SendGrid;

builder.Services.AddGrydNotificationsSendGrid(options =>
{
    options.ApiKey = builder.Configuration["SendGrid:ApiKey"]!;
});

The API key should come from a secret provider. This extension replaces the configured IEmailSender; it does not use SMTP credentials.

EventWebhookPublicKey, EventWebhookTimestampTolerance (default 5 minutes) and EventWebhookMaxBodyBytes (default 1 MiB) configure the signed Event Webhook receiver. See Delivery feedback.


Push Notification Options ​

Options of the push channel. Push.Enabled does not register a provider: reference GrydNotifications.Infrastructure.Firebase and call AddGrydNotificationsFirebase, or register your own IPushNotificationSender (see Channels).

csharp
options.Push.Enabled = true;
options.Push.DefaultTimeToLive = TimeSpan.FromHours(24);
options.Push.AutoRemoveInvalidTokens = true;
options.Push.RequireProvider = true;

Properties ​

PropertyTypeDefaultDescription
EnabledbooltrueEnables the push channel and the stale-token cleanup
DefaultTimeToLiveTimeSpan24hTTL of a message that sets none (Android and browser)
MaxDeviceTokensPerMulticastint500Tokens per provider batch (FCM caps it at 500)
StaleTokenThresholdTimeSpan90 daysA token neither registered again nor used for this long is deactivated; a never-used token counts from its registration
AutoRemoveInvalidTokensbooltrueDeactivates tokens the provider reports as unregistered
RequireProviderboolfalseFails the host start while push is enabled and no provider is registered; off, the host logs a warning

Firebase Configuration ​

AddGrydNotificationsFirebase needs CredentialJson or CredentialPath (the service account); the GOOGLE_APPLICATION_CREDENTIALS variable alone is not enough. FirebaseOptions.MaxDeviceTokensPerMulticast and FirebaseOptions.AutoRemoveInvalidTokens still apply: the lower batch size wins, and either flag turns removal off.


In-App Notification Options ​

Configure the in-app notification channel (drawer/bell notifications + SignalR real-time).

csharp
options.InApp.Enabled = true;
options.InApp.EnableSignalR = true;
options.InApp.HubPath = "/hubs/notifications";
options.InApp.RetentionDays = 90;
options.InApp.MaxUnreadPerUser = 200;

Properties ​

PropertyTypeDefaultDescription
EnabledbooltrueEnables in-app notification channel
RetentionDaysint90Days to retain in-app notifications
MaxUnreadPerUserint200Max unread per user (oldest auto-marked as read)
DefaultTimeToLiveTimeSpan?nullDefault TTL for notifications (null = no expiration)
EnableSignalRbooltrueEnables real-time delivery via SignalR
HubPathstring/hubs/notificationsSignalR hub endpoint path

Retry Options ​

Configure retry policies for failed notification delivery.

csharp
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;

Properties ​

PropertyTypeDefaultDescription
MaxRetriesint3Used by the registered Polly policy; the default queue budget comes from the notification command/entity
BackoffTypeBackoffTypeExponentialBackoff strategy
BaseDelayTimeSpan5sBase delay for the first retry
MaxDelayTimeSpan5minFinal delay cap, including jitter; maximum supported value is 4,294,967,294 ms
UseJitterbooltrueVaries each retry delay by up to ±25% before the final cap
NonRetryableReasonsHashSet<DeliveryFailureReason>see belowFailure reasons that dead-letter without retry in the default queue

For the default queue, SendNotificationCommand.MaxRetries is copied to the notification entity and controls its attempt budget. It defaults to 3; RetryCount counts failed sends, so 3 allows three total sends, while 0 or 1 allows only the initial send. Retry.MaxRetries does not override this entity budget.

Backoff Types ​

TypeFormulaExample (5s base)
FixedbaseDelay5s → 5s → 5s
LinearbaseDelay × completedFailures5s → 10s → 15s
ExponentialbaseDelay × 2^(completedFailures-1)5s → 10s → 20s

The first retry uses BaseDelay. The default processor waits inside a bounded queue worker slot and waits for the entire current batch before dequeuing the next one. A backoff can therefore hold up later batches even when another slot is idle. Stopping during the wait leaves the record Queued without an in-memory queue entry. The volatile queue has no restart recovery scan; enable durable delivery from the start for outbox recovery. The channel sender classifies a recipient refused during the SMTP conversation: 5xx as Bounced and 4xx as ProviderUnavailable. Other provider failures are still Unknown.

Non-Retryable Failure Reasons ​

By default, these permanent failures skip retry entirely:

  • InvalidRecipient — Email address doesn't exist
  • Bounced — The server definitively refused the recipient (5xx)
  • InvalidTemplate — Template syntax error
  • AuthenticationFailed — Provider credential error

Queue Options ​

Configure the in-memory notification processing queue (Channel<T>).

csharp
options.Queue.BatchSize = 10;
options.Queue.PollingInterval = TimeSpan.FromSeconds(5);
options.Queue.MaxConcurrency = 4;

Properties ​

PropertyTypeDefaultDescription
BatchSizeint10Notifications dequeued per batch
PollingIntervalTimeSpan5sPolling interval when queue is empty
MaxConcurrencyint4Concurrent processors consuming the queue
MessageExpirationTimeSpan?nullMax time in queue before discard (null = no limit)

WARNING

The default queue uses Channel<T> in-memory and has no restart recovery. Durable delivery is a separate opt-in PostgreSQL outbox mode: set DurableDelivery = true while keeping PersistNotifications and EnableQueue enabled, apply the durable migration, and register the worker profile. See Durable delivery. The optional GrydNotifications.Scheduling package integrates recurring scheduled jobs with GrydJobs; it does not enable outbox durability.


Health Checks ​

csharp
using GrydNotifications.API;

builder.Services.AddGrydNotificationsHealthChecks();

The check reads the depth of the optional INotificationQueue, when one is registered. A depth above 10,000 or a queue read failure uses the registration's failureStatus. The default is Degraded; ASP.NET Core maps Degraded to HTTP 200 and Unhealthy to HTTP 503 by default. See ASP.NET Core health check status code mapping. Without a registered queue, the check reports that the notifications module is running. These results do not verify SMTP delivery, SignalR connectivity, database connectivity or schema, or background worker liveness.

For a readiness endpoint that fails when the queue is over the threshold or cannot be read, add the ready tag explicitly and choose Unhealthy. The default tags do not include ready:

csharp
using GrydNotifications.API;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

builder.Services.AddGrydNotificationsHealthChecks(
    failureStatus: HealthStatus.Unhealthy,
    tags: ["grydnotifications", "notifications", "ready"]);

app.MapHealthChecks("/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

With ASP.NET Core's default response writer, the response body is the overall status as plain text (Healthy, Degraded, or Unhealthy). Configure a ResponseWriter explicitly if the host needs JSON details for individual checks.


appsettings.json Reference ​

Complete configuration example:

json
{
  "ConnectionStrings": {
    "GrydNotifications": "Host=localhost;Database=gryd_notifications;Username=postgres;Password=postgres"
  },
  "GrydNotifications": {
    "EnableTemplates": true,
    "EnableQueue": true,
    "PersistNotifications": true,
    "NotificationRetentionDays": 90,
    "Email": {
      "DefaultFrom": "noreply@myapp.com",
      "DefaultFromName": "My App",
      "SmtpHost": "smtp.example.com",
      "SmtpPort": 587,
      "SmtpUseSsl": true,
      "SmtpUsername": "<smtp username>",
      "SmtpPassword": "<load from a secret provider>",
      "MaxAttachmentSizeMb": 10,
      "MaxAttachmentsPerEmail": 5,
      "MaxRecipientsPerEmail": 50,
      "BulkBatchSize": 100,
      "BulkDelayBetweenBatches": "00:00:01"
    },
    "Push": {
      "Enabled": false,
      "DefaultTimeToLive": "24:00:00",
      "MaxDeviceTokensPerMulticast": 500,
      "StaleTokenThreshold": "90.00:00:00",
      "AutoRemoveInvalidTokens": true,
      "RequireProvider": false
    },
    "InApp": {
      "Enabled": true,
      "RetentionDays": 90,
      "MaxUnreadPerUser": 200,
      "DefaultTimeToLive": null,
      "EnableSignalR": true,
      "HubPath": "/hubs/notifications"
    },
    "Retry": {
      "MaxRetries": 3,
      "BackoffType": "Exponential",
      "BaseDelay": "00:00:05",
      "MaxDelay": "00:05:00",
      "UseJitter": true
    },
    "Queue": {
      "BatchSize": 10,
      "PollingInterval": "00:00:05",
      "MaxConcurrency": 4,
      "MessageExpiration": null
    }
  }
}

Released under the MIT License.