Multichannel debt collection: technical architecture
Multichannel Debt Collection: A Technical Architecture Deep Dive
Building a multichannel debt collection platform requires orchestrating communication across WhatsApp, email, and SMS while maintaining compliance, reliability, and cost efficiency. In this post, I will walk through the technical architecture we implemented at cobranzas scale, with production-tested patterns and code examples you can adapt.
The Core Challenge
Debt collection sits at the intersection of high regulatory scrutiny and urgent customer communication. A typical multicanal flow looks like this: a payment is missed, the system evaluates channel preference and availability, then sequences messages across WhatsApp, email, and SMS with escalating urgency and legal compliance checks.
The trap most engineering teams fall into is building channel-specific silos. You end up with three separate APIs, three message templates, three delivery tracking systems, and no unified view of customer contact history. The architecture I present here solves this through abstraction layers and event-driven design.
System Architecture Overview
Our platform follows a hexagonal architecture with clear separation between domain logic and channel adapters. At the center sits the Orchestration Engine, surrounded by channel-specific gateways and compliance middleware.
┌─────────────────────────────────────────┐
│ API Gateway / LB │
└─────────────────────────────────────────┘
│
┌─────────────────────────────────────────┐
│ Campaign Orchestration Engine │
│ (Rules, Priorities, Retry Logic) │
└─────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌───────┐ ┌───────┐ ┌───────┐
│WhatsApp│ │ Email │ │ SMS │
│Gateway │ │Gateway│ │Gateway│
└───────┘ └───────┘ └───────┘
│ │ │
└─────────────┴─────────────┘
│
┌─────────┴─────────┐
▼ ▼
┌─────────┐ ┌─────────┐
│ Delivery│ │Compliance│
│ Tracker │ │ Engine │
└─────────┘ └─────────┘
The Message Domain Model
Everything starts with a unified message contract. This abstraction lets us treat channels as interchangeable while preserving channel-specific capabilities.
public sealed class MulticanalMessage
{
public Guid MessageId { get; init; } = Guid.NewGuid();
public required string DebtorId { get; init; }
public required MessageChannel Channel { get; init; }
public required MessagePriority Priority { get; init; }
public required MessageContent Content { get; init; }
public required LegalClassification LegalType { get; init; }
public IReadOnlyList<string> ConsentRecords { get; init; } = [];
public ChannelSpecificPayload? ChannelPayload { get; init; }
// Immutable enforcement for audit trails
public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;
}
public record MessageContent
{
public required string TemplateId { get; init; }
public required Dictionary<string, string> Variables { get; init; }
}
public enum MessageChannel { WhatsApp, Email, Sms }
public enum MessagePriority
{
Informational = 1,
Reminder = 2,
PreLegal = 3,
LegalNotice = 4
}
The ChannelSpecificPayload discriminated union holds WhatsApp interactive buttons, email attachments, or SMS shortcodes without polluting the core domain:
public abstract record ChannelSpecificPayload;
public sealed record WhatsAppPayload(
InteractiveButton? CtaButton,
ListTemplate? ListMessage
) : ChannelSpecificPayload;
public sealed record EmailPayload(
IReadOnlyList<Attachment> Attachments,
string? HtmlBodyOverride
) : ChannelSpecificPayload;
public sealed record SmsPayload(
string? ShortCode,
bool ForceGsmEncoding
) : ChannelSpecificPayload;
Channel Gateway Implementation
Each channel gateway implements a common interface while handling provider quirks internally. Here is the WhatsApp gateway using the official Cloud API with fallback to a regional BSP:
public interface IChannelGateway
{
Task<GatewayResult> SendAsync(
MulticanalMessage message,
CancellationToken ct = default);
Task<DeliveryStatus> PollStatusAsync(
string externalMessageId,
CancellationToken ct = default);
}
public sealed class WhatsAppGateway : IChannelGateway
{
private readonly IWhatsAppCloudApi _cloudApi;
private readonly IBspFallback _bspFallback;
private readonly IRateLimiter _rateLimiter;
private readonly ILogger<WhatsAppGateway> _logger;
// WhatsApp-specific: 80 messages/second per number
private static readonly RateLimitLimits Limits = new(80, TimeSpan.FromSeconds(1));
public async Task<GatewayResult> SendAsync(
MulticanalMessage message,
CancellationToken ct)
{
// Compliance gate: explicit opt-in required for WhatsApp
if (!message.ConsentRecords.Contains("whatsapp_explicit_optin"))
{
return GatewayResult.Blocked("Missing WhatsApp opt-in consent");
}
var payload = BuildCloudApiPayload(message);
await _rateLimiter.AcquireAsync(Limits, ct);
try
{
var response = await _cloudApi.SendTemplateMessageAsync(
to: message.DebtorId, // Phone number
templateName: message.Content.TemplateId,
languageCode: "es_MX",
parameters: MapVariables(message.Content.Variables),
ct);
return GatewayResult.Accepted(
externalId: response.Messages[0].Id,
channelCost: 0.005m); // USD per template
}
catch (WhatsAppApiException ex) when (ex.Code == 131026)
{
// Template not approved or variables mismatch
_logger.LogWarning(ex, "Cloud API rejected template, attempting BSP fallback");
var bspResult = await _bspFallback.SendAsync(payload, ct);
return bspResult with {
ChannelCost = 0.008m // BSP premium pricing
};
}
}
private static CloudApiPayload BuildCloudApiPayload(MulticanalMessage message)
{
var basePayload = new CloudApiPayload(message.Content.TemplateId);
if (message.ChannelPayload is WhatsAppPayload wa)
{
if (wa.CtaButton is not null)
{
basePayload.Components.Add(new ButtonComponent(
wa.CtaButton.Text,
wa.CtaButton.Url));
}
}
return basePayload;
}
}
Notice the pattern: compliance check first, primary provider attempt, structured fallback with cost tracking. This same structure repeats across all three channels with channel-specific constraints.
The Orchestration Engine: Smart Routing
The engine determines which channel to use, when to escalate, and when to suppress. It operates on streaming debt events from our event bus:
public class CollectionOrchestrator : IConsumer<DebtOverdueEvent>
{
private readonly IDebtorProfileRepository _profiles;
private readonly IChannelRouter _router;
private readonly IMessageSequenceEngine _sequences;
private readonly IComplianceEngine _compliance;
public async Task Consume(ConsumeContext<DebtOverdueEvent> context)
{
var evt = context.Message;
var profile = await _profiles.GetAsync(evt.DebtorId);
var overdue = DateTimeOffset.UtcNow - evt.DueDate;
// Build candidate messages for all viable channels
var candidates = _router.EvaluateChannels(profile, evt)
.Select(ch => BuildCandidateMessage(evt, profile, ch))
.ToList();
// Apply legal and regulatory filters
var permitted = await _compliance.FilterPermittedAsync(
candidates,
profile.Jurisdiction);
// Execute sequenced delivery with backoff
var sequence = _sequences.GetOrCreate(evt.DebtorId, evt.DebtId);
await sequence.ExecuteAsync(permitted, new SequenceOptions
{
// Day 1: WhatsApp + Email simultaneously
// Day 3: SMS if no response
// Day 7: Registered mail (legal requirement in MX)
Stages = overdue.TotalDays switch
{
< 3 => new[] {
new Stage([MessageChannel.WhatsApp, MessageChannel.Email], TimeSpan.Zero),
new Stage([MessageChannel.Sms], TimeSpan.FromHours(24))
},
< 7 => new[] {
new Stage([MessageChannel.Sms, MessageChannel.Email], TimeSpan.Zero)
},
_ => new[] {
new Stage([MessageChannel.Email], TimeSpan.Zero) // Pre-legal
}
},
// Stop sequence on payment confirmation
CancellationToken = await _subscribePaymentAsync(evt.DebtId)
});
}
private MulticanalMessage BuildCandidateMessage(
DebtOverdueEvent evt,
DebtorProfile profile,
ChannelEvaluation eval)
{
var template = ResolveTemplate(eval.Channel, evt.OverdueDays, profile.Jurisdiction);
return new MulticanalMessage
{
DebtorId = profile.Id,
Channel = eval.Channel,
Priority = MapPriority(evt),
Content = new MessageContent
{
TemplateId = template.Id,
Variables = new Dictionary<string, string>
{
["debtor_name"] = profile.FirstName,
["amount_due"] = evt.AmountDue.ToString("C"),
["due_date"] = evt.DueDate.ToString("d", profile.Culture),
["payment_url"] = GenerateSignedUrl(evt.DebtId, template.Channel)
}
},
LegalType = template.Classification,
ConsentRecords = profile.ChannelConsents[eval.Channel],
ChannelPayload = eval.Channel switch
{
MessageChannel.WhatsApp => new WhatsAppPayload(
CtaButton: new("Pagar ahora", $"https://pay.example.com/{evt.DebtId}")),
MessageChannel.Email => new EmailPayload(
Attachments: template.RequiresLegalAttachment
? [GenerateLegalNoticePdf(evt)]
: [],
HtmlBodyOverride: null),
_ => null
}
};
}
}
Compliance Engine: The Non-Negotiable Layer
Debt collection regulations—Mexico's LFPDPPP, Brazil's Lei Geral de Proteção de Dados, Colombia's SIC guidelines—impose time windows, content restrictions, and contact frequency limits. Our compliance engine validates every message against active regulations:
public class ComplianceEngine : IComplianceEngine
{
private readonly IRegulationStore _regulations;
private readonly IContactHistory _history;
public async Task<IReadOnlyList<MulticanalMessage>> FilterPermittedAsync(
IReadOnlyList<MulticanalMessage> candidates,
string jurisdiction)
{
var activeReg = await _regulations.GetActiveAsync(jurisdiction);
var recentContacts = await _history.GetRecentAsync(
candidates[0].DebtorId,
TimeSpan.FromDays(7));
var permitted = new List<MulticanalMessage>();
foreach (var msg in candidates)
{
// Time restriction: no calls/messages before 8 AM or after 8 PM
var localTime = TimeZoneConverter.ToLocalTime(
DateTimeOffset.UtcNow,
jurisdiction);
if (localTime.Hour is < 8 or > 20)
{
continue; // Suppress until valid window
}
// Frequency cap: max 3 contact attempts per channel per 7 days
var channelAttempts = recentContacts.Count(c =>
c.Channel == msg.Channel && c.AttemptedAt > DateTimeOffset.UtcNow.AddDays(-7));
if (channelAttempts >= 3)
{
continue;
}
// Content validation: legal notices require specific template approval
if (msg.LegalType == LegalClassification.FormalDemand
&& !msg.Content.TemplateId.StartsWith("LEGAL_"))
{
throw new ComplianceViolationException(
"Formal demand requires LEGAL_ prefixed template");
}
permitted.Add(msg);
}
return permitted;
}
}
Delivery Tracking and Idempotency
At cobranzas volume, duplicate sends destroy trust and incur provider fees. We implement idempotency through deterministic message IDs and conditional writes:
public class IdempotentDeliveryStore : IMessageStore
{
private readonly IDistributedCache _cache;
private readonly IMessageRepository _repository;
public async Task<StoreResult> TryStoreAsync(MulticanalMessage message)
{
// Deterministic idempotency key: debtor + debt + channel + sequence position
var idempotencyKey = ComputeHash(
$"{message.DebtorId}:{message.Content.TemplateId}:{message.CreatedAt:yyyyMMdd}");
var cacheKey = $"idemp:{idempotencyKey}";
// Distributed lock with Redis RedLock
var lockAcquisition = await _lock.TryAcquireAsync(cacheKey, TimeSpan.FromSeconds(30));
if (!lockAcquisition.IsAcquired)
{
return StoreResult.Conflict("Concurrent send detected");
}
try
{
// Double-check persistence layer
var existing = await _repository.GetByIdempotencyAsync(idempotencyKey);
if (existing is not null)
{
return StoreResult.Duplicate(existing);
}
var record = new MessageRecord
{
IdempotencyKey = idempotencyKey,
Status = MessageStatus.Pending,
// ... other fields
};
await _repository.InsertAsync(record);
await _cache.SetAsync(cacheKey, record.Id, TimeSpan.FromHours(24));
return StoreResult.Stored(record);
}
finally
{
await lockAcquisition.ReleaseAsync();
}
}
}
Operational Considerations
Cost optimization: WhatsApp template messages cost $0.005-$0.014 depending on destination country, while SMS ranges $0.002-$0.05. We implemented automatic channel downgrading: if WhatsApp delivery fails with error 131021 (user not on WhatsApp), we cascade to SMS within the same orchestration window, preserving the customer experience at lower cost.
Provider redundancy: Each gateway maintains two provider integrations with circuit breakers. Our email gateway switches between SendGrid and AWS SES based on real-time delivery rate monitoring.
Observability: We emit structured events for every state transition—submitted, accepted by provider, delivered, read, failed with code—into a ClickHouse cluster for collection analytics. Dashboards track cost-per-dollar-collected by channel, the ultimate engineering metric for cobranzas platforms.
Conclusion
Building multicanal debt collection infrastructure demands more than integrating three APIs. The architecture must enforce compliance by construction, handle provider failures transparently, and optimize for business outcomes rather than technical metrics. The patterns here—unified domain models, gateway abstraction, sequenced orchestration, and hard compliance boundaries—have processed millions of collection messages across Latin American markets. Adapt them to your regulatory environment and scale constraints.