ASP.NET Core Interview Question #241

How would you design a background email queue?

Senior ASP.NET Core Real-World Scenarios Senior Advanced

Quick Interview Answer

The request path should create the business state and enqueue an email command rather than waiting for a slow mail server when immediate delivery is unnecessary. A background worker consumes the queue and sends messages.

Detailed Explanation

The request path should create the business state and enqueue an email command rather than waiting for a slow mail server when immediate delivery is unnecessary. A background worker consumes the queue and sends messages.

If email must not be lost when the process crashes, use a durable queue or transactional outbox pattern instead of only an in-memory Channel. Track attempts, apply bounded retries for transient failures, and move permanently failing messages to a failure/dead-letter workflow for investigation.

Design message handling to tolerate duplicate delivery.

Code Example

public record EmailMessage(string To, string Subject, string Body);

// Request path:
await _emailQueue.EnqueueAsync(message, ct);

// Background worker:
await foreach (var message in _emailQueue.ReadAllAsync(stoppingToken))
{
    await _sender.SendAsync(message, stoppingToken);
}