ISO 20022 message handling: pain.001, pacs.008 and camt.053 in C#
Read, build and validate ISO 20022 payment messages safely in .NET: understand the structure of pain.001, pacs.008 and camt.053, validate in three layers (schema, scheme rules, business rules), generate C# classes from XSDs, parse statements into Harbourline's transaction model, and run it all on AWS with S3, SQS and Lambda.
Assumes: .NET 10 LTS · System.Xml / System.Xml.Linq · dotnet-xscgen 3.0.x · AWS SDK for .NET v4 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain what ISO 20022 is (a business model plus message definitions, usually in XML) and read a message identifier such as
pacs.008.001.08. - Describe the structure and purpose of pain.001 (customer credit transfer initiation), pacs.008 (bank-to-bank customer credit transfer), pacs.002 (status report) and camt.053 (account statement), and key elements such as
MsgId,EndToEndId,UETR,IntrBkSttlmAmtandCdtDbtInd. - Validate messages in three layers: XSD schema, market/scheme usage rules (for example CBPR+), and your own business rules; and parse XML securely in .NET.
- Generate C# classes from official XSDs with XmlSchemaClassGenerator (
xscgen), and decide when to use generated classes versusXDocument. - Parse a camt.053 statement into Harbourline's
transactionsmodel withdecimalamounts, and design an AWS pipeline (S3 → SQS → Lambda) for inbound messages.
Prerequisites
- REST API design and Idempotency keys —
EndToEndIdand idempotency go together - Calling partner APIs safely — many ISO 20022 messages arrive through partner channels
- Tools: .NET 10 SDK (or Docker). No AWS account needed
- A full parser-and-test-suite lab (Lab 4.6) is planned for this module but is not written yet (see the module overview); this lesson's code is self-contained
Why this matters in banking
At 16:40 Harbourline Bank's (fictional) payments operations team sees 312 outbound payments rejected by a correspondent bank with reason "invalid postal address". A release earlier that day changed how customer addresses are mapped into pacs.008: the street and town went into free-text AdrLine elements instead of structured fields. The payments are high value and time-critical; customers are calling.
Two days later reconciliation fails: a camt.053 statement from a partner bank contains an amount of 1250.5 and the import code, which used double, posts 1250.4999999. And a security review finds that the XML parser would happily expand external entities, so a malicious file could read local files.
ISO 20022 is now the language of payments: high-value schemes, cross-border messaging over Swift and many domestic schemes use it. Every bank developer who touches payments needs to read these messages, build them correctly and validate them defensively.
The idea in plain language
ISO 20022 is a standard for financial messages. It has two parts:
- A business model: agreed meanings for things like "debtor", "creditor agent" or "interbank settlement amount".
- Message definitions built from that model, usually published as XML schemas (XSDs). A JSON representation also exists, but XML dominates in payments today.
Message identifiers follow a pattern: pacs.008.001.08
| Part | Meaning |
|---|---|
pacs | Business area: payments clearing and settlement |
008 | Message number: FI to FI customer credit transfer |
001 | Variant (001 is the base variant) |
08 | Version |
The business areas you meet most often:
| Area | Typical messages | Who talks to whom |
|---|---|---|
pain (payments initiation) | pain.001 credit transfer initiation, pain.002 status report, pain.008 direct debit initiation | Corporate customer ↔ its bank |
pacs (clearing and settlement) | pacs.008 customer credit transfer, pacs.009 bank transfer, pacs.002 status, pacs.004 return | Bank ↔ bank / clearing system |
camt (cash management) | camt.052 intraday report, camt.053 statement, camt.054 debit/credit notification, camt.056 cancellation request | Bank ↔ customer, bank ↔ bank |
head | head.001 Business Application Header (BAH) | Wraps a message with routing information |
A payment's life in messages: a business customer uploads a pain.001 with 200 salary payments; Harbourline validates it and, for each payment, sends a pacs.008 to the clearing system or a correspondent; status comes back in pacs.002; the customer gets a pain.002 status report, and at end of day a camt.053 statement lists the booked entries.
Analogy: ISO 20022 is like a strictly formatted international shipping form. Every box has a defined meaning ("consignee", "declared value", "country of origin"), so every customs office in the world reads it the same way. The XSD is the rule that says which boxes exist and what fits in them. A scheme's usage guidelines (for example CBPR+ for cross-border payments over Swift) are the extra rules of one particular shipping company: "box 7 is mandatory for us" or "use the structured address boxes, not the free-text lines".
Three ideas recur in every message:
- Identification at several levels:
MsgId(this message),InstrId(instruction between two parties),EndToEndId(set by the original payer and carried unchanged to the payee) andUETR(a UUID that tracks the payment across every bank on the way). - Amounts with a currency attribute:
<IntrBkSttlmAmt Ccy="GBP">1250.50</IntrBkSttlmAmt>. Alwaysdecimal. - Parties and agents: debtor and creditor are the customers; debtor agent and creditor agent are their banks, identified by BIC (
BICFI).
What problem the AWS services solve
AWS has no ISO 20022 parser; that is your .NET code. AWS gives you the plumbing around it.
| Need | AWS building block | Notes |
|---|---|---|
| Receive files or messages | S3 (files via SFTP, see SWIFT and file-based integration); Amazon MQ or SQS (messages, see Core banking integration); API Gateway (ISO 20022 over HTTPS) | Keep the original bytes |
| Immutable copy of every message | S3 with versioning and Object Lock | Evidence for disputes and audits |
| Decouple receiving from processing | S3 event notification → SQS (with DLQ) | Backpressure and retries |
| Parse and validate | Lambda (dotnet10) or ECS service | XSD validation of large files is CPU-heavy; size memory accordingly |
| Store results | DynamoDB/Aurora for payments; S3 + Athena for analytics | Map into the canonical model |
SQS messages are limited in size (about 1 MiB since 2025), so do not put large XML documents in the queue: put the S3 key in the message and keep the document in S3.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
xsd.exe to generate classes | dotnet-xscgen (XmlSchemaClassGenerator) | xsd.exe ships with the .NET Framework SDK; xscgen is a cross-platform .NET tool that works with modern .NET |
| BizTalk / Logic Apps Integration Account schemas and maps | Your .NET code in Lambda/ECS, optionally Step Functions | No managed XML mapping service; code is easier to test anyway |
| Azure Blob + Event Grid trigger | S3 + event notification → SQS → Lambda | Same pattern |
| Blob immutability policies | S3 Object Lock | Compliance mode cannot be shortened, even by root |
XmlReaderSettings / XDocument | Exactly the same | Your .NET XML skills transfer unchanged |
Architecture
Security-boundary view. Inbound XML is untrusted input, even from a partner bank:
- Parse with DTDs prohibited and no external resolver (no XXE).
- Enforce maximum file size and maximum number of transactions before parsing everything.
- Keep the original bytes immutable (Object Lock) and process a copy.
- The Lambda role can read
inbound/, writerejected/and the domain store, and nothing else. - Statements contain personal data (names, IBANs); encrypt buckets with KMS, restrict access and set retention according to your records policy.
Step-by-step implementation
Get the right schemas and usage guidelines
Download the XSDs for the exact versions you exchange from the ISO 20022 message catalogue at iso20022.org (for example pacs.008.001.08). Market practice groups publish usage guidelines that restrict the base message: CBPR+ for cross-border payments over Swift (published on Swift's MyStandards platform), and scheme rulebooks for domestic systems. Store schemas in the repository, versioned, and never fetch them at runtime.
Decide: generated classes or XDocument?
- Generated classes (from XSDs with
xscgen): strongly typed, good for building outbound messages and for large, stable integrations. The classes are big; pacs.008 alone produces hundreds of types. XDocument/XmlReader: lightweight, good for reading the handful of fields you need, and for streaming very large statements.
Many banks use generated classes for outbound and targeted XPath-like reading for inbound.
Parse securely
Create an XmlReader with DtdProcessing = Prohibit, XmlResolver = null, and a MaxCharactersInDocument limit. Load it into XDocument or deserialize from it. Never call XDocument.Load(path) on untrusted data without explicit settings, and never enable DTD processing for inbound files.
Validate in three layers
- Schema (XSD): structure, mandatory elements, data types, patterns, lengths. Use
XmlSchemaSetandXmlReaderSettings.ValidationType = Schema, collecting all errors rather than stopping at the first. - Scheme / usage rules: for example CBPR+ requires a
UETR; from 14 November 2026 CBPR+ no longer allows fully unstructured postal addresses (structured or "hybrid" only, with town name and country mandatory) ⚠ VERIFY the current status: some industry sources report that Swift deferred parts of Standards Release 2026. - Business rules:
NbOfTxsequals the number of transactions;CtrlSumequals the sum of amounts; IBAN checksums; currency is one you support; amounts within limits;EndToEndIdnot already processed (idempotency); settlement date is a business day.
Reject with precise reason codes; ISO 20022 has an external code list of status reason codes (for example AC01 incorrect account number, AM05 duplication) that you return in pacs.002/pain.002.
Map to the canonical model
Translate ISO elements into Harbourline's domain: payments.end_to_end_id ← PmtId/EndToEndId; payments.amount ← IntrBkSttlmAmt (decimal); payments.currency ← @Ccy; transactions.amount ← camt Amt with sign from CdtDbtInd (CRDT positive, DBIT negative). Keep the mapping in one class with tests (an anti-corruption layer).
Produce status messages and keep evidence
For every inbound instruction, produce a status (ACCP, RJCT with reason). Store the original, the parsed result and the status message together with the same correlation ID, so operations can answer "what happened to payment X?" in one query.
AWS Console instructions
The pipeline uses services from earlier lessons; the relevant console steps:
- Inbound bucket: S3 → Create bucket
hl-m04-iso-inbound-111122223333→ Block all public access on → Bucket Versioning enabled → Object Lock enabled (only possible at creation, or later via support for existing buckets) → default encryption SSE-KMS. - Queue: SQS → Create queue
hl-m04-iso-inbound(standard) → Dead-letter queue enabled pointing athl-m04-iso-inbound-dlq, maximum receives 5 → access policy allowings3.amazonaws.comtoSendMessagewithaws:SourceArnof the bucket. - Notification: bucket → Properties → Event notifications → Create → prefix
inbound/, suffix.xml, event All object create events → destination SQS queue. - Function: Lambda → Create function → runtime .NET 10 → add trigger SQS with batch size 1–10 and Report batch item failures enabled.
AWS CLI
PROFILE=learn-sandbox
REGION=us-east-1
BUCKET=hl-m04-iso-inbound-111122223333
# Bucket with Object Lock (implies versioning) and blocked public access
aws s3api create-bucket --bucket $BUCKET --object-lock-enabled-for-bucket --profile $PROFILE --region $REGION
aws s3api put-public-access-block --bucket $BUCKET \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true \
--profile $PROFILE --region $REGION
aws s3api put-bucket-tagging --bucket $BUCKET \
--tagging 'TagSet=[{Key=Project,Value=cea-lab},{Key=Lab,Value=m04-l20},{Key=Environment,Value=learn},{Key=Owner,Value=you}]' \
--profile $PROFILE --region $REGION
# Queues
aws sqs create-queue --queue-name hl-m04-iso-inbound-dlq --profile $PROFILE --region $REGION
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url $(aws sqs get-queue-url --queue-name hl-m04-iso-inbound-dlq --query QueueUrl --output text --profile $PROFILE --region $REGION) \
--attribute-names QueueArn --query Attributes.QueueArn --output text --profile $PROFILE --region $REGION)
aws sqs create-queue --queue-name hl-m04-iso-inbound \
--attributes "{\"RedrivePolicy\":\"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":\\\"5\\\"}\",\"VisibilityTimeout\":\"180\"}" \
--profile $PROFILE --region $REGION
# Upload a test message (fictional) and list what arrived
aws s3 cp samples/pacs008-sample.xml s3://$BUCKET/inbound/2026/11/18/pacs008-sample.xml --profile $PROFILE --region $REGION
aws s3api list-object-versions --bucket $BUCKET --prefix inbound/ --profile $PROFILE --region $REGIONThe queue policy and bucket notification (aws s3api put-bucket-notification-configuration) follow the same pattern as in Webhooks; see IaC below for the complete wiring.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.S3;
using Amazon.CDK.AWS.S3.Notifications;
using Amazon.CDK.AWS.SQS;
using Constructs;
namespace Harbourline.Payments.Infra;
public sealed class IsoInboundStack : Stack
{
public IsoInboundStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
var bucket = new Bucket(this, "Inbound", new BucketProps
{
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
Encryption = BucketEncryption.KMS_MANAGED,
EnforceSSL = true,
Versioned = true,
ObjectLockEnabled = true,
ObjectLockDefaultRetention = ObjectLockRetention.Governance(Duration.Days(1)), // lab: 1 day, governance mode
RemovalPolicy = RemovalPolicy.RETAIN
});
var dlq = new Queue(this, "Dlq", new QueueProps { RetentionPeriod = Duration.Days(14) });
var queue = new Queue(this, "InboundQueue", new QueueProps
{
VisibilityTimeout = Duration.Seconds(180),
DeadLetterQueue = new DeadLetterQueue { Queue = dlq, MaxReceiveCount = 5 },
Encryption = QueueEncryption.SQS_MANAGED
});
bucket.AddEventNotification(EventType.OBJECT_CREATED, new SqsDestination(queue),
new NotificationKeyFilter { Prefix = "inbound/", Suffix = ".xml" });
var fn = new Function(this, "Parser", new FunctionProps
{
Runtime = Runtime.DOTNET_10,
Handler = "Harbourline.Payments.IsoInbound::Harbourline.Payments.IsoInbound.Function::HandleAsync",
Code = Code.FromAsset("../../src/Harbourline.Payments.IsoInbound/bin/Release/net10.0/publish"),
MemorySize = 1024,
Timeout = Duration.Seconds(60),
Environment = new Dictionary<string, string> { ["MAX_FILE_BYTES"] = "10485760" }
});
bucket.GrantRead(fn, "inbound/*");
bucket.GrantPut(fn, "rejected/*");
fn.AddEventSource(new SqsEventSource(queue, new SqsEventSourceProps
{
BatchSize = 5,
ReportBatchItemFailures = true
}));
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m04-l20");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
Amazon.CDK.Tags.Of(this).Add("Owner", "you");
}
}Runtime.DOTNET_10 requires a recent CDK release ⚠ VERIFY it exists in Amazon.CDK.Lib 2.277.0; otherwise use new Runtime("dotnet10", RuntimeFamily.DOTNET_CORE).
Complete code
A self-contained .NET 10 console app. It builds a pacs.008 with XDocument, validates it against a small teaching XSD (a subset written for this lesson, not the official schema), runs business rules, rejects a deliberately broken message with reasons, and parses a camt.053 statement into Harbourline transactions. No packages required.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
</Project>using System.Globalization;
using System.Numerics;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
// ---------- 1. Build a pacs.008 for one fictional GBP payment ----------
var payment = new OutboundPayment(
PaymentId: "PAY-019a7c1e-0000-7000-8000-000000000001",
EndToEndId: "HLB-E2E-20261118-0001",
Uetr: Guid.Parse("8a562c67-ca16-48ba-b074-65581be6f001"),
Amount: 1250.50m, Currency: "GBP", SettlementDate: new DateOnly(2026, 11, 18),
DebtorName: "Alex Example", DebtorIban: "GB33BUKB20201555555555", DebtorBic: "HLBKGB2LXXX",
DebtorTown: "Leeds", DebtorCountry: "GB",
CreditorName: "Sam Sample", CreditorIban: "GB82WEST12345698765432", CreditorBic: "WESTGB2L",
CreditorTown: "York", CreditorCountry: "GB",
Remittance: "Invoice 4471");
var xml = Pacs008Builder.Build("HLB-MSG-20261118-000001", new DateTimeOffset(2026, 11, 18, 9, 30, 0, TimeSpan.Zero), [payment]);
Console.WriteLine($"Built pacs.008 with {xml.Descendants().Count()} elements");
var validator = new IsoValidator();
Report("Valid message", validator.Validate(Encoding.UTF8.GetBytes(xml.ToString())));
// ---------- 2. Break it in three ways and validate again ----------
var broken = new XDocument(xml);
XNamespace ns = Pacs008Builder.Ns;
broken.Descendants(ns + "NbOfTxs").Single().Value = "2"; // business rule: count mismatch
broken.Descendants(ns + "CdtrAcct").Descendants(ns + "IBAN").Single().Value = "GB82WEST12345698765433"; // checksum
broken.Descendants(ns + "IntrBkSttlmAmt").Single().Value = "12,50"; // schema: not a decimal
Report("Broken message", validator.Validate(Encoding.UTF8.GetBytes(broken.ToString())));
// ---------- 3. XXE attempt is refused ----------
const string xxe = """
<?xml version="1.0"?>
<!DOCTYPE d [<!ENTITY x SYSTEM "file:///etc/passwd">]>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08">&x;</Document>
""";
Report("XXE attempt", validator.Validate(Encoding.UTF8.GetBytes(xxe)));
// ---------- 4. Parse a camt.053 statement into Harbourline transactions ----------
foreach (var t in Camt053Parser.Parse(Encoding.UTF8.GetBytes(Samples.Camt053), accountId: "ACC-0000123456"))
Console.WriteLine($"{t.BookingDate:yyyy-MM-dd} {t.Amount,10:+0.00;-0.00} {t.Currency} {t.Type,-12} {t.CounterpartyName} | {t.Reference}");
static void Report(string label, IReadOnlyList<string> errors)
{
Console.WriteLine($"{label}: {(errors.Count == 0 ? "ACCEPTED" : "REJECTED")}");
foreach (var e in errors) Console.WriteLine($" - {e}");
}
// =====================================================================
public sealed record OutboundPayment(string PaymentId, string EndToEndId, Guid Uetr, decimal Amount, string Currency,
DateOnly SettlementDate, string DebtorName, string DebtorIban, string DebtorBic, string DebtorTown, string DebtorCountry,
string CreditorName, string CreditorIban, string CreditorBic, string CreditorTown, string CreditorCountry, string Remittance);
public static class Pacs008Builder
{
public const string Ns = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08";
public static XDocument Build(string msgId, DateTimeOffset createdAt, IReadOnlyList<OutboundPayment> payments)
{
XNamespace ns = Ns;
static string Amt(decimal d) => d.ToString("0.00###", CultureInfo.InvariantCulture); // never culture-specific
// Structured postal address (TwnNm + Ctry) instead of free-text AdrLine.
XElement Party(string name, string town, string country) =>
new(ns + "Party",
new XElement(ns + "Nm", name),
new XElement(ns + "PstlAdr", new XElement(ns + "TwnNm", town), new XElement(ns + "Ctry", country)));
return new XDocument(new XDeclaration("1.0", "UTF-8", null),
new XElement(ns + "Document",
new XElement(ns + "FIToFICstmrCdtTrf",
new XElement(ns + "GrpHdr",
new XElement(ns + "MsgId", msgId),
new XElement(ns + "CreDtTm", createdAt.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)),
new XElement(ns + "NbOfTxs", payments.Count.ToString(CultureInfo.InvariantCulture)),
new XElement(ns + "SttlmInf", new XElement(ns + "SttlmMtd", "CLRG"))),
payments.Select(p => new XElement(ns + "CdtTrfTxInf",
new XElement(ns + "PmtId",
new XElement(ns + "InstrId", p.PaymentId[..Math.Min(35, p.PaymentId.Length)]),
new XElement(ns + "EndToEndId", p.EndToEndId),
new XElement(ns + "UETR", p.Uetr.ToString("D"))),
new XElement(ns + "IntrBkSttlmAmt", new XAttribute("Ccy", p.Currency), Amt(p.Amount)),
new XElement(ns + "IntrBkSttlmDt", p.SettlementDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)),
new XElement(ns + "ChrgBr", "SLEV"),
new XElement(ns + "Dbtr", Party(p.DebtorName, p.DebtorTown, p.DebtorCountry).Elements()),
new XElement(ns + "DbtrAcct", new XElement(ns + "Id", new XElement(ns + "IBAN", p.DebtorIban))),
new XElement(ns + "DbtrAgt", new XElement(ns + "FinInstnId", new XElement(ns + "BICFI", p.DebtorBic))),
new XElement(ns + "CdtrAgt", new XElement(ns + "FinInstnId", new XElement(ns + "BICFI", p.CreditorBic))),
new XElement(ns + "Cdtr", Party(p.CreditorName, p.CreditorTown, p.CreditorCountry).Elements()),
new XElement(ns + "CdtrAcct", new XElement(ns + "Id", new XElement(ns + "IBAN", p.CreditorIban))),
new XElement(ns + "RmtInf", new XElement(ns + "Ustrd", p.Remittance)))))));
}
}
public sealed class IsoValidator
{
private readonly XmlSchemaSet _schemas = new();
public IsoValidator()
{
using var reader = XmlReader.Create(new StringReader(Samples.TeachingPacs008Xsd));
_schemas.Add(Pacs008Builder.Ns, reader);
_schemas.Compile();
}
public IReadOnlyList<string> Validate(byte[] document, int maxBytes = 10 * 1024 * 1024)
{
var errors = new List<string>();
if (document.Length > maxBytes) return [$"File too large: {document.Length} bytes"];
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit, // XXE defence
XmlResolver = null, // never fetch external resources
MaxCharactersInDocument = maxBytes,
ValidationType = ValidationType.Schema,
Schemas = _schemas
};
settings.ValidationEventHandler += (_, e) =>
errors.Add($"XSD line {e.Exception?.LineNumber}: {e.Message}");
XDocument doc;
try
{
using var reader = XmlReader.Create(new MemoryStream(document), settings);
doc = XDocument.Load(reader, LoadOptions.SetLineInfo);
}
catch (XmlException ex)
{
return [$"Not well-formed or forbidden construct: {ex.Message}"];
}
errors.AddRange(BusinessRules(doc)); // run even after schema errors so operations sees every problem
return errors;
}
private static IEnumerable<string> BusinessRules(XDocument doc)
{
XNamespace ns = Pacs008Builder.Ns;
var txs = doc.Descendants(ns + "CdtTrfTxInf").ToList();
if (int.TryParse(doc.Descendants(ns + "NbOfTxs").FirstOrDefault()?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var n)
&& n != txs.Count)
yield return $"NbOfTxs is {n} but message contains {txs.Count} transactions";
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var tx in txs)
{
var e2e = tx.Descendants(ns + "EndToEndId").FirstOrDefault()?.Value ?? "";
if (!seen.Add(e2e)) yield return $"Duplicate EndToEndId {e2e} (AM05)";
foreach (var iban in tx.Descendants(ns + "IBAN"))
if (!Iban.IsValid(iban.Value)) yield return $"Invalid IBAN checksum {Iban.Mask(iban.Value)} (AC01)";
var amt = tx.Element(ns + "IntrBkSttlmAmt");
if (amt is not null && decimal.TryParse(amt.Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value))
{
var ccy = (string?)amt.Attribute("Ccy");
if (ccy is not ("GBP" or "EUR")) yield return $"Unsupported currency {ccy}";
if (decimal.Round(value, 2) != value) yield return $"Amount {value} has more than 2 decimals for {ccy}";
}
}
}
}
public static class Iban
{
// ISO 13616 mod-97 check: move first 4 chars to the end, letters → numbers, remainder must be 1.
public static bool IsValid(string iban)
{
var s = iban.Replace(" ", "", StringComparison.Ordinal).ToUpperInvariant();
if (s.Length is < 15 or > 34 || !s.All(char.IsAsciiLetterOrDigit)) return false;
var rearranged = s[4..] + s[..4];
var digits = new StringBuilder();
foreach (var c in rearranged) digits.Append(char.IsAsciiDigit(c) ? c.ToString() : (c - 'A' + 10).ToString(CultureInfo.InvariantCulture));
return BigInteger.Parse(digits.ToString(), CultureInfo.InvariantCulture) % 97 == 1;
}
public static string Mask(string iban) => iban.Length > 8 ? iban[..4] + new string('*', iban.Length - 8) + iban[^4..] : "****";
}
// =====================================================================
public sealed record Transaction(string TransactionId, string AccountId, DateOnly BookingDate, DateOnly ValueDate,
decimal Amount, string Currency, string Type, string Channel, string CounterpartyName, string Reference, string Status);
public static class Camt053Parser
{
private static readonly XNamespace Ns = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.08";
public static IEnumerable<Transaction> Parse(byte[] document, string accountId)
{
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null };
using var reader = XmlReader.Create(new MemoryStream(document), settings);
var doc = XDocument.Load(reader);
foreach (var ntry in doc.Descendants(Ns + "Ntry"))
{
var amtEl = ntry.Element(Ns + "Amt") ?? throw new FormatException("Entry without Amt");
var amount = decimal.Parse(amtEl.Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
var isCredit = ntry.Element(Ns + "CdtDbtInd")?.Value switch
{
"CRDT" => true,
"DBIT" => false,
var other => throw new FormatException($"Unknown CdtDbtInd '{other}'")
};
var status = ntry.Element(Ns + "Sts")?.Element(Ns + "Cd")?.Value;
var tx = ntry.Descendants(Ns + "TxDtls").FirstOrDefault();
var counterparty = isCredit
? tx?.Element(Ns + "RltdPties")?.Element(Ns + "Dbtr")?.Descendants(Ns + "Nm").FirstOrDefault()?.Value
: tx?.Element(Ns + "RltdPties")?.Element(Ns + "Cdtr")?.Descendants(Ns + "Nm").FirstOrDefault()?.Value;
yield return new Transaction(
TransactionId: Guid.CreateVersion7().ToString(),
AccountId: accountId,
BookingDate: DateOnly.Parse(ntry.Element(Ns + "BookgDt")!.Element(Ns + "Dt")!.Value, CultureInfo.InvariantCulture),
ValueDate: DateOnly.Parse(ntry.Element(Ns + "ValDt")!.Element(Ns + "Dt")!.Value, CultureInfo.InvariantCulture),
Amount: isCredit ? amount : -amount,
Currency: (string?)amtEl.Attribute("Ccy") ?? throw new FormatException("Amt without Ccy"),
Type: isCredit ? "transfer_in" : "transfer_out",
Channel: "batch",
CounterpartyName: counterparty ?? "",
Reference: tx?.Descendants(Ns + "EndToEndId").FirstOrDefault()?.Value ?? ntry.Element(Ns + "AcctSvcrRef")?.Value ?? "",
Status: status == "BOOK" ? "booked" : "pending");
}
}
}
// =====================================================================
public static class Samples
{
// A small TEACHING subset of pacs.008.001.08 written for this lesson. Real systems use the official XSD
// from the ISO 20022 catalogue plus the usage guideline of their scheme.
public const string TeachingPacs008Xsd = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08"
targetNamespace="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08"
elementFormDefault="qualified">
<xs:element name="Document">
<xs:complexType><xs:sequence><xs:element name="FIToFICstmrCdtTrf" type="Transfer"/></xs:sequence></xs:complexType>
</xs:element>
<xs:complexType name="Transfer"><xs:sequence>
<xs:element name="GrpHdr" type="GroupHeader"/>
<xs:element name="CdtTrfTxInf" type="TxInfo" maxOccurs="unbounded"/>
</xs:sequence></xs:complexType>
<xs:complexType name="GroupHeader"><xs:sequence>
<xs:element name="MsgId" type="Max35Text"/>
<xs:element name="CreDtTm" type="xs:dateTime"/>
<xs:element name="NbOfTxs" type="Max15NumericText"/>
<xs:element name="SttlmInf"><xs:complexType><xs:sequence>
<xs:element name="SttlmMtd"><xs:simpleType><xs:restriction base="xs:string">
<xs:enumeration value="INDA"/><xs:enumeration value="INGA"/><xs:enumeration value="COVE"/><xs:enumeration value="CLRG"/>
</xs:restriction></xs:simpleType></xs:element>
</xs:sequence></xs:complexType></xs:element>
</xs:sequence></xs:complexType>
<xs:complexType name="TxInfo"><xs:sequence>
<xs:element name="PmtId"><xs:complexType><xs:sequence>
<xs:element name="InstrId" type="Max35Text" minOccurs="0"/>
<xs:element name="EndToEndId" type="Max35Text"/>
<xs:element name="UETR" type="UUIDv4"/>
</xs:sequence></xs:complexType></xs:element>
<xs:element name="IntrBkSttlmAmt" type="Amount"/>
<xs:element name="IntrBkSttlmDt" type="xs:date"/>
<xs:element name="ChrgBr"><xs:simpleType><xs:restriction base="xs:string">
<xs:enumeration value="DEBT"/><xs:enumeration value="CRED"/><xs:enumeration value="SHAR"/><xs:enumeration value="SLEV"/>
</xs:restriction></xs:simpleType></xs:element>
<xs:element name="Dbtr" type="Party"/>
<xs:element name="DbtrAcct" type="Account"/>
<xs:element name="DbtrAgt" type="Agent"/>
<xs:element name="CdtrAgt" type="Agent"/>
<xs:element name="Cdtr" type="Party"/>
<xs:element name="CdtrAcct" type="Account"/>
<xs:element name="RmtInf" minOccurs="0"><xs:complexType><xs:sequence>
<xs:element name="Ustrd" type="Max140Text" maxOccurs="unbounded"/>
</xs:sequence></xs:complexType></xs:element>
</xs:sequence></xs:complexType>
<xs:complexType name="Party"><xs:sequence>
<xs:element name="Nm" type="Max140Text"/>
<xs:element name="PstlAdr"><xs:complexType><xs:sequence>
<xs:element name="TwnNm" type="Max35Text"/>
<xs:element name="Ctry" type="CountryCode"/>
</xs:sequence></xs:complexType></xs:element>
</xs:sequence></xs:complexType>
<xs:complexType name="Account"><xs:sequence><xs:element name="Id"><xs:complexType><xs:sequence>
<xs:element name="IBAN" type="IBAN"/>
</xs:sequence></xs:complexType></xs:element></xs:sequence></xs:complexType>
<xs:complexType name="Agent"><xs:sequence><xs:element name="FinInstnId"><xs:complexType><xs:sequence>
<xs:element name="BICFI" type="BIC"/>
</xs:sequence></xs:complexType></xs:element></xs:sequence></xs:complexType>
<xs:complexType name="Amount"><xs:simpleContent><xs:extension base="AmountValue">
<xs:attribute name="Ccy" type="CurrencyCode" use="required"/>
</xs:extension></xs:simpleContent></xs:complexType>
<xs:simpleType name="AmountValue"><xs:restriction base="xs:decimal">
<xs:minInclusive value="0"/><xs:totalDigits value="18"/><xs:fractionDigits value="5"/>
</xs:restriction></xs:simpleType>
<xs:simpleType name="Max35Text"><xs:restriction base="xs:string"><xs:minLength value="1"/><xs:maxLength value="35"/></xs:restriction></xs:simpleType>
<xs:simpleType name="Max140Text"><xs:restriction base="xs:string"><xs:minLength value="1"/><xs:maxLength value="140"/></xs:restriction></xs:simpleType>
<xs:simpleType name="Max15NumericText"><xs:restriction base="xs:string"><xs:pattern value="[0-9]{1,15}"/></xs:restriction></xs:simpleType>
<xs:simpleType name="CurrencyCode"><xs:restriction base="xs:string"><xs:pattern value="[A-Z]{3}"/></xs:restriction></xs:simpleType>
<xs:simpleType name="CountryCode"><xs:restriction base="xs:string"><xs:pattern value="[A-Z]{2}"/></xs:restriction></xs:simpleType>
<xs:simpleType name="IBAN"><xs:restriction base="xs:string"><xs:pattern value="[A-Z]{2}[0-9]{2}[a-zA-Z0-9]{1,30}"/></xs:restriction></xs:simpleType>
<xs:simpleType name="BIC"><xs:restriction base="xs:string"><xs:pattern value="[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3}){0,1}"/></xs:restriction></xs:simpleType>
<xs:simpleType name="UUIDv4"><xs:restriction base="xs:string"><xs:pattern value="[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}"/></xs:restriction></xs:simpleType>
</xs:schema>
""";
// A trimmed, fictional camt.053.001.08 statement with one credit and one debit.
public const string Camt053 = """
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08">
<BkToCstmrStmt>
<GrpHdr><MsgId>STMT-20261118-0001</MsgId><CreDtTm>2026-11-18T22:00:00Z</CreDtTm></GrpHdr>
<Stmt>
<Id>HLB-STMT-ACC0000123456-20261118</Id>
<CreDtTm>2026-11-18T22:00:00Z</CreDtTm>
<Acct><Id><IBAN>GB33BUKB20201555555555</IBAN></Id><Ccy>GBP</Ccy></Acct>
<Ntry>
<Amt Ccy="GBP">2150.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
<BookgDt><Dt>2026-11-18</Dt></BookgDt><ValDt><Dt>2026-11-18</Dt></ValDt>
<AcctSvcrRef>HLB-REF-778812</AcctSvcrRef>
<BkTxCd><Prtry><Cd>TRF</Cd></Prtry></BkTxCd>
<NtryDtls><TxDtls>
<Refs><EndToEndId>SALARY-NOV-2026-0042</EndToEndId></Refs>
<RltdPties><Dbtr><Pty><Nm>Northwind Payroll Ltd</Nm></Pty></Dbtr></RltdPties>
</TxDtls></NtryDtls>
</Ntry>
<Ntry>
<Amt Ccy="GBP">1250.50</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
<BookgDt><Dt>2026-11-18</Dt></BookgDt><ValDt><Dt>2026-11-18</Dt></ValDt>
<AcctSvcrRef>HLB-REF-778813</AcctSvcrRef>
<BkTxCd><Prtry><Cd>TRF</Cd></Prtry></BkTxCd>
<NtryDtls><TxDtls>
<Refs><EndToEndId>HLB-E2E-20261118-0001</EndToEndId></Refs>
<RltdPties><Cdtr><Pty><Nm>Sam Sample</Nm></Pty></Cdtr></RltdPties>
</TxDtls></NtryDtls>
</Ntry>
</Stmt>
</BkToCstmrStmt>
</Document>
""";
}Expected output (abridged):
Built pacs.008 with 40 elements
Valid message: ACCEPTED
Broken message: REJECTED
- XSD line 14: The 'urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08:IntrBkSttlmAmt' element is invalid - The value '12,50' is invalid according to its datatype ...
- NbOfTxs is 2 but message contains 1 transactions
- Invalid IBAN checksum GB82**************5433 (AC01)
XXE attempt: REJECTED
- Not well-formed or forbidden construct: For security reasons DTD is prohibited in this XML document. ...
2026-11-18 +2150.00 GBP transfer_in Northwind Payroll Ltd | SALARY-NOV-2026-0042
2026-11-18 -1250.50 GBP transfer_out Sam Sample | HLB-E2E-20261118-0001Generating classes from official XSDs
For outbound messages at scale, generate classes instead of hand-building XML:
# Install the XmlSchemaClassGenerator command-line tool
dotnet tool install --global dotnet-xscgen
# Generate C# for pacs.008.001.08 into a namespace you control
xscgen -n "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.08=Harbourline.Payments.Iso20022.Pacs008" \
-o src/Harbourline.Payments.Iso20022/Generated \
--nullable --netCore \
schemas/pacs.008.001.08.xsdThen serialise with XmlSerializer and validate the output against the same XSD before sending. Check the tool's --help for the option names in your version ⚠ VERIFY the flags above against dotnet-xscgen 3.0.x.
Code explained line by line
OutboundPaymentmirrors Harbourline'spaymentstable:decimalamount, ISO currency,EndToEndId, and aUetrthat is a random (version 4) UUID, as the tracking standard expects.Pacs008Builder.Nsis the XML namespace that identifies the message type and version. Getting the namespace wrong is the most common reason a valid-looking document fails validation.Amt(...)formats withCultureInfo.InvariantCulture. On a server with a French or German culture,ToString()would produce1250,50, which is invalid ISO 20022.CreDtTmincludes a UTC offset; ISO 20022 date-times carry time zone information, and you should always generate them explicitly.- Elements are created in schema order. XSD sequences are ordered;
CdtrbeforeCdtrAgtis a schema error even if every value is right. PstlAdruses structuredTwnNmandCtryelements instead of free-textAdrLine, which is what CBPR+ now expects.IsoValidatorcompiles the schema once (expensive) and reuses theXmlSchemaSetfor every message.DtdProcessing.ProhibitandXmlResolver = nullblock XXE and "billion laughs" attacks;MaxCharactersInDocumentcaps memory use.ValidationEventHandlercollects all schema errors instead of throwing on the first, so operations sees every problem at once.BusinessRuleschecks what XSD cannot:NbOfTxsmatches the content,EndToEndIdis unique in the message, IBAN mod-97 checksums, supported currency, and 2 decimal places for GBP/EUR (the XSD allows 5).Iban.Maskkeeps full IBANs out of error messages and logs.Camt053Parserreads only the fields it needs withXDocument.CdtDbtIndgives the sign: amounts in ISO 20022 are always positive, the indicator says which direction.- Unknown
CdtDbtIndvalues throw: an unexpected value in a statement is a reason to stop and investigate, not to guess. Sts/CdofBOOKmaps tobooked;PDNG(pending) andINFOentries are treated differently in real reconciliation.
Security considerations
⚠ Learning shortcut — not for production
The validator uses a small teaching XSD written for this lesson. Production validation uses the official XSD for the exact message version and your scheme's usage guideline (for CBPR+, the rules published on Swift MyStandards), plus your business rules. Do not ship the teaching schema.
⚠ Learning shortcut — not for production
The demo loads whole documents into memory with XDocument. Bulk pain.001 files and month-end camt.053 statements can be hundreds of megabytes; in production, stream them with XmlReader (reading one CdtTrfTxInf or Ntry at a time with XNode.ReadFrom) and enforce size limits before reading.
- XML is attack surface. Prohibit DTDs, disable resolvers, cap size, and never transform untrusted XML with XSLT that allows scripts or
document()calls. - Personal data. Names, addresses and IBANs are personal data under UK GDPR. Mask them in logs, encrypt at rest with KMS, restrict access to the inbound bucket and set retention per your records policy.
- Integrity. Keep the original message bytes immutable (S3 Object Lock) and record a SHA-256 hash; you may need to prove exactly what was received.
- Authenticity. Messages arriving over Swift, a scheme network or SFTP are authenticated by that channel (and sometimes signed); verify that before parsing (see SWIFT and file-based integration).
- Sanctions screening. Every outbound and inbound payment message passes through sanctions screening on names, addresses and BICs; structured addresses improve screening accuracy. Screening is a compliance function, outside this lesson.
Banking use case
Harbourline's payments hub (fictional):
- Corporate customers upload
pain.001files by SFTP or via API. The hub validates each file in the three layers, sends apain.002acknowledgement within minutes, and creates onepaymentsrow per instruction keyed byEndToEndIdplus debtor account (idempotent re-uploads). - Outbound payments generate
pacs.008via generated classes, are validated against the official XSD and the scheme guideline, screened, and submitted.pacs.002responses updatepayments.status(submitted→settledorrejectedwith reason). - Statements from correspondent banks arrive as
camt.053and feed reconciliation in the data platform; theEndToEndIdin the statement is the join key back topayments. - Monitoring: metrics for messages accepted and rejected per reason code; an alarm when the rejection rate for one partner exceeds 2% in an hour, which is exactly the signal that would have caught the address-mapping release in minutes.
Common mistakes
- Using
doubleor culture-specific formatting for amounts. UsedecimalandInvariantCultureeverywhere. - Ignoring element order. XSD sequences are ordered.
- Wrong namespace or version.
pacs.008.001.08andpacs.008.001.10are different schemas. - Validating only against the XSD. Scheme rules and business rules catch most real rejections.
- Free-text addresses. CBPR+ requires structured or hybrid addresses.
- Losing identifiers. Overwriting
EndToEndIdor generating a newUETRon retry breaks tracking and reconciliation. - Default XML settings on untrusted input. Always configure the reader explicitly.
- Putting full XML in SQS messages. Store in S3; send the key.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
The element 'X' has invalid child element 'Y' | Elements out of schema order or wrong namespace | Compare with the XSD sequence; check every element uses the message namespace |
The value '12,50' is invalid according to its datatype | Culture-specific decimal formatting | Format with InvariantCulture |
For security reasons DTD is prohibited | Partner sends a DOCTYPE | Ask the partner to remove it; do not enable DTD processing |
| Schema compiles but nothing validates | ValidationType not set, or schema namespace differs from document | Set ValidationType.Schema; match targetNamespace |
| Reconciliation off by a cent | Floating-point arithmetic | decimal end to end |
| Messages rejected by correspondent with address errors | Unstructured address lines | Map to structured StrtNm, BldgNb, PstCd, TwnNm, Ctry |
| Lambda times out on large statements | Whole-document load and validation | Stream with XmlReader; increase memory (more CPU); split processing |
Cost and cleanup
- Free: the console app and validation run locally with no AWS account.
- Optional AWS pipeline: S3, SQS and Lambda at lab volumes sit within typical free allowances; KMS-managed keys (
aws/s3) have no monthly key fee. Object Lock retention means objects cannot be deleted until retention expires; the lab uses 1 day in governance mode.
# After the 1-day retention has passed (or with governance bypass permission):
aws s3api list-object-versions --bucket hl-m04-iso-inbound-111122223333 --profile learn-sandbox \
--query '{Objects: Versions[].{Key:Key,VersionId:VersionId}}' --output json > versions.json
aws s3api delete-objects --bucket hl-m04-iso-inbound-111122223333 --delete file://versions.json \
--bypass-governance-retention --profile learn-sandbox
aws s3api delete-bucket --bucket hl-m04-iso-inbound-111122223333 --profile learn-sandbox
aws sqs delete-queue --queue-url $(aws sqs get-queue-url --queue-name hl-m04-iso-inbound --query QueueUrl --output text --profile learn-sandbox) --profile learn-sandbox
aws sqs delete-queue --queue-url $(aws sqs get-queue-url --queue-name hl-m04-iso-inbound-dlq --query QueueUrl --output text --profile learn-sandbox) --profile learn-sandbox
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--query 'ResourceTagMappingList[].ResourceARN' --profile learn-sandboxDelete markers may also need removing (DeleteMarkers in the same listing) before the bucket deletes.
Exercises
- 🟢 Guided: Run the app. Change
ChrgBrin the builder toXXXXand observe the schema error. Then add a second payment with the sameEndToEndIdand observe the business-rule error. - 🟡 Challenge: Write a
Pacs002Builderthat produces a status report for the broken message: group statusRJCT, and oneTxInfAndStsper transaction withOrgnlEndToEndId,TxStsRJCTand reason codeAC01for the bad IBAN. Use namespaceurn:iso:std:iso:20022:tech:xsd:pacs.002.001.10. - 🔴 Live problem: A correspondent bank sends a 600 MB
camt.053once a month. Your Lambda (1,024 MB memory) fails with out-of-memory errors. Redesign the parser and the AWS processing so it handles 2 GB files with constant memory, and explain how you would make the processing restartable if it fails halfway.
Assignment
Create a docs/iso20022-mapping.md in your portfolio repository: a table mapping each Harbourline payments and transactions field to its ISO 20022 element path in pacs.008.001.08 and camt.053.001.08, the validation layer that checks it, and the reason code returned on failure. Add three anonymised sample messages (valid, schema-invalid, business-invalid) as test fixtures.
Solutions
XXXX fails the ChrgBr enumeration in the XSD: "The 'ChrgBr' element is invalid - The value 'XXXX' is invalid according to its datatype ... The Enumeration constraint failed." Adding a second payment with the same EndToEndId passes the XSD (it has no uniqueness rule) but fails the business rule "Duplicate EndToEndId (AM05)", and NbOfTxs is correct because the builder counts the list. Why it matters: schema validity is necessary but not sufficient; duplicates are a business concept.
public static XDocument BuildPacs002(string originalMsgId, IEnumerable<(string EndToEndId, string? Reason)> results)
{
XNamespace ns = "urn:iso:std:iso:20022:tech:xsd:pacs.002.001.10";
var list = results.ToList();
var groupStatus = list.All(r => r.Reason is null) ? "ACCP" : list.All(r => r.Reason is not null) ? "RJCT" : "PART";
return new XDocument(new XElement(ns + "Document",
new XElement(ns + "FIToFIPmtStsRpt",
new XElement(ns + "GrpHdr",
new XElement(ns + "MsgId", $"STS-{Guid.CreateVersion7():N}"[..35]),
new XElement(ns + "CreDtTm", DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture))),
new XElement(ns + "OrgnlGrpInfAndSts",
new XElement(ns + "OrgnlMsgId", originalMsgId),
new XElement(ns + "OrgnlMsgNmId", "pacs.008.001.08"),
new XElement(ns + "GrpSts", groupStatus)),
list.Select(r => new XElement(ns + "TxInfAndSts",
new XElement(ns + "OrgnlEndToEndId", r.EndToEndId),
new XElement(ns + "TxSts", r.Reason is null ? "ACCP" : "RJCT"),
r.Reason is null ? null : new XElement(ns + "StsRsnInf",
new XElement(ns + "Rsn", new XElement(ns + "Cd", r.Reason))))))));
}Why: the status report refers back to the original by OrgnlMsgId and OrgnlEndToEndId, which is how the sender correlates. PART signals partial acceptance in a batch. Validate the result against the official pacs.002 XSD before relying on element order ⚠ VERIFY.
Stream instead of loading: XmlReader with secure settings, advance to each Ntry element and read it with XNode.ReadFrom into a small XElement, map it and write it out in batches (for example 1,000 transactions per DynamoDB batch or per Parquet file). Do XSD validation in the same streaming pass (the validating reader validates as it reads). Lambda can do this with constant memory if the S3 object is read as a stream (GetObjectAsync response stream) rather than downloaded into a byte array; if processing may exceed Lambda's 15-minute limit, move it to an ECS task triggered by EventBridge or Step Functions. For restartability, checkpoint progress (statement ID and last processed entry sequence or AcctSvcrRef) in DynamoDB and make writes idempotent with a deterministic key per entry, so a restart can skip what is already stored.
Knowledge check
Answer: pain is payments initiation (customer ↔ bank), pacs is payments clearing and settlement (bank ↔ bank or clearing system), camt is cash management (statements, notifications, cancellations).
Answer: EndToEndId is set by the original payer (up to 35 characters) and passed unchanged to the payee for their reconciliation. UETR is a UUID version 4 that uniquely tracks the payment across all banks in the chain.
Answer: XSDs check structure and data types only. Scheme usage guidelines (such as CBPR+) and business rules (control sums, IBAN checksums, duplicates, supported currencies, structured addresses) add constraints the base schema does not express.
Answer: Amounts are positive; CdtDbtInd is CRDT for credits and DBIT for debits. Your mapping applies the sign.
Answer: DtdProcessing = DtdProcessing.Prohibit and XmlResolver = null.
Interview questions
- "Explain pain.001 to camt.053 for one payment." — The customer sends pain.001; the bank creates pacs.008 to the scheme or correspondent; pacs.002 reports status; pain.002 informs the customer; camt.053 shows the booked entry, with
EndToEndIdlinking them all. - "How do you validate ISO 20022 messages?" — Three layers: official XSD, scheme usage guidelines, business rules; collect all errors; return ISO reason codes; keep the original immutable.
- "How do you handle a 1 GB statement file?" — Stream with
XmlReader, validate while reading, process entries in batches, checkpoint, make writes idempotent, and use ECS rather than Lambda if it can exceed 15 minutes. - "What's changing with addresses in cross-border payments?" — CBPR+ is moving away from unstructured addresses to structured or hybrid formats (town and country mandatory); check the current Swift timeline.
- "Generated classes or XDocument?" — Generated classes for building complex outbound messages safely; targeted
XDocument/XmlReaderfor reading a few fields or streaming large inbound files.
Certification practice
A bank receives ISO 20022 XML files of up to 50 MB in an S3 bucket and must process each file reliably, retry failures and keep failed files for investigation. Which architecture is MOST appropriate?
A. S3 event notification invoking Lambda directly with the file content in the event.
B. S3 event notification to an SQS queue with a dead-letter queue; Lambda reads the S3 key from the message and streams the object from S3.
C. Lambda polling the bucket every minute with ListObjectsV2.
D. An SQS message containing the full XML file sent by the uploader.
Answer: B. SQS buffers and retries, the DLQ keeps poison messages, and Lambda streams the large object from S3. A: S3 events contain metadata, not file content. C is inefficient and racy. D exceeds SQS message size limits for large files.
A .NET Lambda function generates payment XML. In testing it works, but in production some amounts appear as 1250,50 and are rejected. What is the MOST likely fix?
A. Increase Lambda memory.
B. Format amounts with CultureInfo.InvariantCulture.
C. Use double instead of decimal.
D. Set the Lambda timeout to 15 minutes.
Answer: B. Culture-specific formatting depends on the environment; invariant formatting guarantees a dot as the decimal separator. A and D are unrelated. C introduces rounding errors.
Regulators require a bank to prove the exact content of payment messages it received for seven years, with no possibility of deletion or alteration, even by administrators. Which S3 configuration meets this requirement?
A. Versioning with MFA Delete.
B. S3 Object Lock in compliance mode with a seven-year retention period.
C. S3 Object Lock in governance mode with a seven-year retention period.
D. A bucket policy denying s3:DeleteObject to all users.
Answer: B. Compliance mode prevents any user, including root, from deleting or shortening retention. A and C can be bypassed by sufficiently privileged users. D can be changed by an administrator.
Completion checklist
- I can read an ISO 20022 message identifier and name the pain/pacs/camt messages in a payment's life
- I can explain MsgId, EndToEndId and UETR
- I ran the demo and saw schema, business-rule and XXE rejections
- I can parse camt.053 entries into transactions with correct signs and
decimal - I know how to generate classes from official XSDs
- I ran the cleanup steps (if I deployed) and confirmed nothing tagged
Project=cea-labremains
Key takeaways
- ISO 20022 messages are identified as area.number.variant.version; pain, pacs and camt cover initiation, interbank and reporting.
- Validate in three layers: official XSD, scheme usage guidelines, business rules; return ISO reason codes.
- Parse untrusted XML securely, use
decimaland invariant formatting, and preserve identifiers end to end. - Structured addresses are now expected in cross-border payments; track scheme deadlines.
- On AWS: immutable S3 storage, SQS with DLQ, and streaming parsers in Lambda or ECS.
Further reading
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Open Banking and PSD2-style APIs: consent, OAuth 2.0/OIDC and FAPI basics
Understand how a bank exposes account and payment APIs to licensed third parties: the consent lifecycle, the redirect flow with PAR and PKCE, strong customer authentication, certificate-bound tokens and the FAPI 2.0 Security Profile, and how those pieces map onto API Gateway mTLS, Lambda authorizers and a consent store on AWS.
SWIFT and file-based integration: SFTP with AWS Transfer Family, PGP and checksums
Exchange batch payment and statement files with partners safely: understand where Swift and scheme file channels fit, run SFTP into S3 with AWS Transfer Family (or a free local SFTP server), encrypt and decrypt with OpenPGP in C#, verify SHA-256 manifests and S3 checksums, and process each file exactly once.