IC Improve Code Recipes

Recipe 17.5 · C#

The Alert Manager as a Modern Worker Service

Problem

CFATS Manager's alerts are the part of the product that reaches people who are not logged in. When a piece of security equipment has been out of service for more than four hours, the facility security officer gets an e-mail. After 24 hours, the corporate security officer is copied. Overdue training and missing daily reports follow similar rules. A Windows service, CFATSAlertManager, does this on a timer. It works, and it is also the code with the most latent failure modes in the product.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

From CFATS Manager, abridged.

C#
// From CFATS Manager: CFATSAlertManager\CFATSAlertManager.cs
// lines 146-182 and 393-428 (abridged, condensed, re-wrapped)
Timer timer = new Timer();

protected override void OnStart(string[] args)
{
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 30000;
    timer.Enabled = true;
}

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
    ConfigurationManager.RefreshSection("appSettings");
    // ... read TimerInterval and update timer.Interval ...

    //set ClientID to 1 for now since there is only one client
    int ClientID = 1;
    LoadAlerts(ClientID);
}

// inside ProcessOutageRange1, for each row:
if (R1_AlertLevel == 1)
{
    ObjectState EmailState = SendAlertLevelOne(
        R1_OutageID, R1_Status, this.CurrentFSO.Email);
    if (EmailState.ErrorOccurred)
    {
        LogMessage("Send Email Failed: " + EmailState.ErrorMessage);
        return false;
    }
    int AlertEmailID = manager.InsertAlertEmail(R1_AlertID, /*...*/);
    if (manager.State.ErrorOccurred) { return false; }
    manager.UpdateAlert(R1_AlertID, R1_AlertLevel + 1, /*...*/);
    // ...
}

Four problems hide in here:

  1. Overlapping ticks. System.Timers.Timer raises Elapsed on the thread pool whether or not the last tick finished. A slow SMTP server and a 30-second interval let two passes run at once and e-mail the same people twice.
  2. Send, then record. The e-mail goes out first, and the alert level is raised afterwards. If the update fails, the next tick sends the same e-mail again, every 30 seconds, until someone notices.
  3. One failure stops everything. return false on the first failed e-mail abandons the rest of that facility's alerts, and the caller ignores the return value.
  4. Rules buried in SQL strings. The 4-hour and 24-hour thresholds live inside SQL constants (DATEADD(hh,-4,SYSDATETIME())), duplicated per range and per alert type. ClientID = 1 is hard-coded, as it is in the SQL Agent job.

OnStop was empty, and nothing in OnElapsedTime caught exceptions. System.Timers.Timer swallows exceptions thrown from its Elapsed handler, so a failure doesn't crash the service. It just disappears.

The improved recipe

Packages: Microsoft.Extensions.Hosting and, to run as a Windows service, Microsoft.Extensions.Hosting.WindowsServices. First the rules and the contracts:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Cfats.Alerts;

public enum AlertKind { Outage, Training, DailyReport }

[Flags]
public enum Recipients { None = 0, Fso = 1, Cso = 2, Others = 4 }

public sealed record OpenAlert(
    int AlertId, int FacilityId, AlertKind Kind,
    int ObjectId, int Level, DateTimeOffset OpenedAt);

public sealed record EscalationStep(
    AlertKind Kind, int FromLevel, TimeSpan After, Recipients To);

public sealed class EscalationPolicy(IEnumerable<EscalationStep> steps)
{
    private readonly EscalationStep[] _steps = steps.ToArray();

    // The CFATS Manager outage rules, expressed as data.
    public static EscalationPolicy Default { get; } = new(
    [
        new(AlertKind.Outage, 1, TimeSpan.FromHours(4),
            Recipients.Fso),
        new(AlertKind.Outage, 2, TimeSpan.FromHours(24),
            Recipients.Fso | Recipients.Cso),
    ]);

    public EscalationStep? NextStep(OpenAlert a, DateTimeOffset now) =>
        _steps.FirstOrDefault(s =>
            s.Kind == a.Kind &&
            s.FromLevel == a.Level &&
            now - a.OpenedAt >= s.After);
}

public interface IAlertStore
{
    Task<IReadOnlyList<OpenAlert>> GetOpenAlertsAsync(
        CancellationToken ct);

    // UPDATE ... SET AlertLevel = @to WHERE AlertID = @id
    //   AND AlertLevel = @from; returns false if someone else won.
    Task<bool> TryAdvanceAsync(
        int alertId, int from, int to, CancellationToken ct);

    Task<IReadOnlyList<string>> GetAddressesAsync(
        int facilityId, Recipients to, CancellationToken ct);

    Task RecordEmailAsync(int alertId, int level,
        IReadOnlyList<string> to, bool sent, CancellationToken ct);
}

public interface IAlertNotifier
{
    Task SendAsync(OpenAlert alert, int newLevel,
        IReadOnlyList<string> to, CancellationToken ct);
}

Then the worker:

C#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ImproveCode.Cfats.Alerts;

public sealed class AlertWorkerOptions
{
    public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1);
}

public sealed class AlertEscalationWorker(
    IAlertStore store,
    IAlertNotifier notifier,
    EscalationPolicy policy,
    TimeProvider clock,
    IOptions<AlertWorkerOptions> options,
    ILogger<AlertEscalationWorker> log) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stop)
    {
        using PeriodicTimer timer = new(options.Value.Interval, clock);
        do
        {
            try
            {
                await RunOnceAsync(stop);
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                log.LogError(ex, "Alert pass failed; retrying next tick");
            }
        }
        while (await timer.WaitForNextTickAsync(stop));
    }

    public async Task RunOnceAsync(CancellationToken ct)
    {
        DateTimeOffset now = clock.GetUtcNow();
        IReadOnlyList<OpenAlert> alerts = await store
            .GetOpenAlertsAsync(ct);

        foreach (OpenAlert alert in alerts)
        {
            EscalationStep? step = policy.NextStep(alert, now);
            if (step is null)
            {
                continue;
            }

            int next = alert.Level + 1;
            if (!await store.TryAdvanceAsync(
                    alert.AlertId, alert.Level, next, ct))
            {
                continue; // another instance already handled it
            }

            IReadOnlyList<string> to = await store.GetAddressesAsync(
                alert.FacilityId, step.To, ct);

            bool sent = false;
            try
            {
                await notifier.SendAsync(alert, next, to, ct);
                sent = true;
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                log.LogWarning(ex, "Alert {AlertId} level {Level} e-mail "
                    + "failed", alert.AlertId, next);
            }

            await store.RecordEmailAsync(
                alert.AlertId, next, to, sent, ct);
        }
    }
}

Hosting it as a Windows service, as a usage snippet:

C#
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(o =>
    o.ServiceName = "CFATS Alert Manager");
builder.Services.Configure<AlertWorkerOptions>(
    builder.Configuration.GetSection("Alerts"));
builder.Services.Configure<SmtpOptions>(
    builder.Configuration.GetSection("Smtp"));
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton(EscalationPolicy.Default);
builder.Services.AddSingleton<IAlertStore, SqlAlertStore>();
builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();
builder.Services.AddSingleton<IAlertNotifier, AlertEmailNotifier>();
builder.Services.AddHostedService<AlertEscalationWorker>();
await builder.Build().RunAsync();

SqlAlertStore is your implementation of IAlertStore over the existing tblAlert and tblAlertEmail tables.

How it works

PeriodicTimer cannot overlap. WaitForNextTickAsync returns only after the previous pass has finished, so a slow pass delays the next one instead of running beside it. The stop token is the host's shutdown signal: stopping the service cancels the wait and lets the current pass end cleanly. That is what the empty OnStop never did. IOptions replaces re-reading appSettings on every tick.

The order of operations is reversed. The worker first claims the escalation with a conditional update (WHERE AlertLevel = @from). Only the caller that changed the row gets true, so two service instances, or two overlapping passes, can't both send. Then it sends. Then it records the attempt, sent or not, in the alert e-mail table. If SMTP is down, the level has still advanced and the failure is logged and recorded. The user sees one missed e-mail instead of an e-mail every 30 seconds. That is a deliberate choice of at-most-once delivery. For alerts that must arrive, add a retry job that re-sends rows recorded with sent = false.

One failed e-mail no longer stops the loop. The catch logs the failure and moves on to the next alert. The outer catch in ExecuteAsync keeps a database outage from killing the service. It logs and tries again on the next tick.

The thresholds are data. EscalationPolicy.Default holds the product's two outage rules. Training and daily-report rules are more rows, not more SQL constants, and a per-facility policy can be loaded from the existing alert-setting tables. Because the worker takes a TimeProvider, a test can open an alert, advance a fake clock by 4 hours, call RunOnceAsync, and assert who was e-mailed. I ran exactly that check with in-memory fakes while writing this chapter. Nobody could test the original without waiting four real hours.

Variations and pitfalls

  • Let SQL find the candidates. GetOpenAlertsAsync should still filter in SQL (open alerts with level below the maximum). The policy decides only which step, not which of a million rows to load.
  • Store times in UTC. The original compared datetime columns written with DateTime.Now against SYSDATETIME(). That is fine on one server in one time zone and wrong twice a year at the daylight-saving change. Use datetime2 with SYSUTCDATETIME(), or datetimeoffset.
  • Remove ClientID = 1. Loop over clients, or make the client part of OpenAlert. A hard-coded tenant is the easiest assumption to forget when a second customer signs.
  • Log somewhere a person reads. The original appended to logfile.txt beside the executable, without a lock and without rotation. Use ILogger with the Windows Event Log or Serilog (Chapter 4).
  • Hangfire or Quartz.NET make sense when you need many schedules or a dashboard. One fixed-interval loop doesn't need them (Chapter 14).