Recipe 9.4 · C#
Queueing and Retrying
Problem
Sending mail inline in a web request couples the user's experience to the mail relay. When the relay is slow, the page is slow. When the relay is down, the user gets an error for an action that actually succeeded, such as placing an order. And a transient failure, like a relay that says "try again later," is treated the same as a permanent one, like a mailbox that does not exist.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
try
{
SaveOrder(order);
EmailHelper.Send(order.Email, "Order received", body);
}
catch (Exception ex)
{
lblMessage.Text = "Your order could not be placed.";
LogHelper.Write(ex.ToString());
}
When the send fails, the order is saved but the user is told it was not, and often places it again.
The improved recipe
The request puts the message on an in-process queue and returns. A hosted background service reads the queue, sends with retries and exponential backoff for transient failures, and logs permanent failures without retrying them. The queue uses System.Threading.Channels (covered in depth in Chapter 14).
NuGet packages: MailKit, Microsoft.Extensions.Hosting.Abstractions.
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using MailKit;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MimeKit;
namespace ImproveCode.Email;
public sealed class EmailQueue
{
private readonly Channel<MimeMessage> _channel =
Channel.CreateBounded<MimeMessage>(
new BoundedChannelOptions(capacity: 1000)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true
});
public ValueTask EnqueueAsync(
MimeMessage message, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(message);
return _channel.Writer.WriteAsync(message, ct);
}
public ChannelReader<MimeMessage> Reader => _channel.Reader;
}
public sealed class EmailDispatcher : BackgroundService
{
private const int MaxAttempts = 5;
private readonly EmailQueue _queue;
private readonly IEmailSender _sender;
private readonly ILogger<EmailDispatcher> _logger;
public EmailDispatcher(
EmailQueue queue,
IEmailSender sender,
ILogger<EmailDispatcher> logger)
{
_queue = queue;
_sender = sender;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken ct)
{
await foreach (var message in _queue.Reader.ReadAllAsync(ct))
{
await SendWithRetryAsync(message, ct);
}
}
private async Task SendWithRetryAsync(
MimeMessage message, CancellationToken ct)
{
for (int attempt = 1; ; attempt++)
{
try
{
await _sender.SendAsync(message, ct);
return;
}
catch (Exception ex)
when (IsTransient(ex) && attempt < MaxAttempts)
{
var delay = TimeSpan.FromSeconds(
Math.Pow(2, attempt) + Random.Shared.NextDouble());
_logger.LogWarning(ex,
"Send of {MessageId} failed (attempt {Attempt}); " +
"retrying in {Delay}",
message.MessageId, attempt, delay);
await Task.Delay(delay, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogError(ex,
"Giving up on {MessageId} to {To} after {Attempt} " +
"attempt(s)", message.MessageId, message.To, attempt);
return;
}
}
}
public static bool IsTransient(Exception ex) => ex switch
{
SmtpCommandException cmd => (int)cmd.StatusCode is >= 400
and < 500,
SmtpProtocolException => true,
ServiceNotConnectedException => true,
SocketException => true,
IOException => true,
TimeoutException => true,
_ => false
};
}
A usage snippet for registration and for the request path:
builder.Services.AddSingleton<EmailQueue>();
builder.Services.AddHostedService<EmailDispatcher>();
// In the order endpoint, after the order is committed:
await emailQueue.EnqueueAsync(confirmation, ct);
return Results.Created($"/orders/{order.Id}", order);
How it works
The bounded channel holds up to 1,000 messages. When it is full, EnqueueAsync waits instead of dropping mail or growing memory without limit; under normal load it completes immediately. SingleReader = true lets the channel use a faster implementation because only the dispatcher reads.
EmailDispatcher runs for the life of the application. ReadAllAsync waits without spinning when the queue is empty and ends cleanly when the host shuts down and cancels the token.
IsTransient is where the judgment lives. SMTP reply codes in the 400s mean "temporary, try again" (mailbox busy, greylisting, rate limit). Codes in the 500s mean "permanent" (no such user, message rejected), and retrying them only gets your server flagged. Network-level failures, a dropped connection and timeouts are treated as transient. Everything else goes to the final catch, which logs the failure with the message ID and recipients and moves on, so one bad message cannot block the queue.
Backoff doubles from 2 seconds to 16 seconds over five attempts, with up to a second of random jitter so that a burst of failures does not retry in lockstep. Chapter 5 shows the same policy with Polly if you already use it.
Variations and pitfalls
- In-memory means losable. If the process restarts, queued messages are gone. For mail that must not be lost, such as legal notices or password resets, write it to an outbox table in the same transaction as the business change and have the dispatcher poll the table. That is the transactional outbox pattern, and it is a small table:
CREATE TABLE dbo.EmailOutbox
(
EmailOutboxId BIGINT IDENTITY(1,1) NOT NULL
CONSTRAINT PK_EmailOutbox PRIMARY KEY,
MessageMime VARBINARY(MAX) NOT NULL,
CreatedUtc DATETIME2(3) NOT NULL
CONSTRAINT DF_EmailOutbox_Created DEFAULT SYSUTCDATETIME(),
Attempts INT NOT NULL CONSTRAINT DF_EmailOutbox_Att DEFAULT 0,
NextAttemptUtc DATETIME2(3) NULL,
SentUtc DATETIME2(3) NULL,
LastError NVARCHAR(2000) NULL
);
- Serialize the whole MIME message.
message.WriteTo(stream)gives you the exact bytes to store inMessageMime, andMimeMessage.Load(stream)reads them back. Attachments and headers survive the round trip. - Batch sends. For a newsletter-sized batch, keep one MailKit client connected and send many messages through it. Reconnect every few hundred messages; many relays limit messages per session.
- Rate limits. Hosted mail services limit messages per second. Add a
Task.Delayor aSystem.Threading.RateLimitinglimiter in the dispatcher loop rather than finding out from 421 replies. - Graceful shutdown. Messages still in the channel at shutdown are lost unless you drain it. Chapter 14 shows how to give a hosted service time to finish.