Complexity: โญโญโญโญโญ (Expert) | Time to Learn: 3-4 hours
A comprehensive banking system demonstrating Railway Oriented Programming (ROP), Domain-Driven Design (DDD), and advanced security patterns including fraud detection, multi-factor authentication, and audit trails.
graph TB
START[Create Account] --> DEPOSIT[Deposit Funds]
DEPOSIT --> WITHDRAW[Withdraw Request]
WITHDRAW --> FRAUD{Fraud Check}
FRAUD -->|Suspicious| FREEZE[๐ Freeze Account]
FRAUD -->|Clean| LIMIT{Daily Limit OK?}
LIMIT -->|Exceeded| DENY[โ Deny Transaction]
LIMIT -->|OK| MFA{Amount > $1,000?}
MFA -->|Yes| VERIFY[๐ฑ Require MFA]
MFA -->|No| PROCESS[Process Withdrawal]
VERIFY -->|Success| PROCESS
VERIFY -->|Failed| DENY
PROCESS --> NOTIFY[๐ง Send Notification]
FREEZE --> ALERT[๐จ Security Alert]
style PROCESS fill:#90EE90
style DENY fill:#FFB6C6
style FREEZE fill:#FFD700
style ALERT fill:#FF6B6B
style VERIFY fill:#E1F5FF
This advanced example demonstrates enterprise-grade banking features:
- ๐ Security First - Multi-layered fraud detection and prevention
- ๐จ Real-time Monitoring - Pattern detection and anomaly alerts
- โ๏ธ Compliance - Daily limits, overdraft rules, audit trails
- ๐ Error Recovery - Automatic freeze on suspicious activity
- ๐ Parallel Processing - Concurrent fraud checks for transfers
classDiagram
class BankAccount {
+AccountId Id
+CustomerId CustomerId
+AccountType Type
+AccountStatus Status
+Money Balance
+Money DailyWithdrawalLimit
+Money OverdraftLimit
+List~Transaction~ Transactions
+Deposit() Result~BankAccount~
+Withdraw() Result~BankAccount~
+Transfer() Result~BankAccount~
+Freeze() Result~BankAccount~
+CalculateInterest() Result~Money~
}
class Transaction {
+TransactionId Id
+TransactionType Type
+Money Amount
+DateTime Timestamp
+string Description
}
class Money {
+decimal Amount
+string Currency
+TryCreate() Result~Money~
}
BankAccount "1" *-- "many" Transaction
BankAccount --> Money
Transaction --> Money
class FraudDetectionService {
+AnalyzeTransactionAsync() Task~Result~bool~~
+RequiresMFA() bool
+DetectSuspiciousPattern() bool
}
class BankingWorkflow {
+ProcessWithdrawalAsync() Task~Result~BankAccount~~
+ProcessTransferAsync() Task~Result~(BankAccount, BankAccount)~~
}
BankingWorkflow --> BankAccount
BankingWorkflow --> FraudDetectionService
stateDiagram-v2
[*] --> Active: Open Account
Active --> Frozen: Fraud Detected
Active --> Frozen: Manual Freeze
Frozen --> Active: Review Complete
Frozen --> Active: Manual Unfreeze
Active --> Closed: Close Account
Frozen --> Closed: Close Account
Closed --> [*]
note right of Frozen
โ ๏ธ All transactions blocked
Requires security review
Notifications sent
end note
note right of Active
โ
Normal operations
Daily limits enforced
Fraud monitoring active
end note
note right of Closed
โน๏ธ Balance must be $0
Cannot reopen
Archive transactions
end note
flowchart TB
TX[New Transaction] --> AMOUNT{Amount > $5,000?}
AMOUNT -->|Yes| MANUAL[๐ Manual Review Required]
AMOUNT -->|No| FREQ{High Frequency?}
FREQ -->|>10/hour| FREEZE[๐ Auto-Freeze]
FREQ -->|Normal| PATTERN{Unusual Pattern?}
PATTERN -->|Yes| MFA[๐ฑ Require MFA]
PATTERN -->|No| APPROVE[โ
Approve]
MANUAL --> REVIEW[Security Team Review]
REVIEW --> APPROVE
MFA -->|Verified| APPROVE
MFA -->|Failed| DENY[โ Deny]
FREEZE --> ALERT[๐จ Alert Security]
style APPROVE fill:#90EE90
style DENY fill:#FFB6C6
style FREEZE fill:#FFD700
style ALERT fill:#FF6B6B
- AccountId: Unique identifier for bank accounts
- TransactionId: Unique identifier for transactions
- CustomerId: Unique identifier for customers
- Money: Represents monetary amounts with precision
- Transaction: Represents individual account transactions (deposit, withdrawal, transfer, fee, interest)
- BankAccount: Aggregate root managing account state, balance, and transaction history
- FraudDetectionService: Analyzes transactions for suspicious patterns and validates customer identity
- BankingWorkflow: Orchestrates complex banking operations with fraud detection and validation
Clean transaction processing with automatic validation:
return await account.Deposit(amount, "Salary")
.Ensure(acc => acc.Status == AccountStatus.Active,
Error.Validation("Account not active"))
.Bind(acc => acc.Withdraw(withdrawAmount, "Rent"))
.Match(
onSuccess: acc => $"Balance: {acc.Balance} โ
",
onFailure: err => $"Failed: {err.Detail} โ"
);What's happening:
- Deposit salary (validates amount, updates balance)
- Ensure account is active (business rule check)
- Withdraw rent (checks limits, validates funds)
- Match result (handle success or failure)
If any check fails, subsequent operations are skipped! ๐ฏ
Real-time security analysis integrated into the transaction flow:
return await account.ToResult()
.EnsureAsync(
async acc => await _fraudDetection.AnalyzeTransactionAsync(
acc, amount, "withdrawal", cancellationToken),
Error.Forbidden("Fraud check failed - transaction blocked")
)
.Bind(acc => acc.Withdraw(amount, description))
.RecoverOnFailureAsync(
predicate: error => error.Code == "fraud.detected",
func: async () => {
await account.Freeze("Suspicious activity detected");
await _notificationService.AlertSecurityTeam(account.Id);
return account;
}
);Fraud Detection Rules:
| Rule | Threshold | Action |
|---|---|---|
| ๐ฐ Large Amount | > $5,000 | Manual review required |
| โก High Frequency | > 10 transactions/hour | Auto-freeze account |
| ๐ฏ Pattern Detection | 3+ round amounts in 24h | Trigger MFA |
| ๐ฑ MFA Required | Withdrawal > $1,000 | Require verification code |
Concurrent validation for performance and security:
var result = await ValidateFromAccountAsync(fromAccount, amount, ct)
.ParallelAsync(ValidateToAccountAsync(toAccount, amount, ct))
.WhenAllAsync()
.BindAsync((fromValid, toValid) =>
ProcessTransferAsync(fromAccount, toAccount, amount, ct), ct);Benefits:
- โก Faster - Both accounts checked simultaneously
- ๐ Secure - All checks must pass before transfer
- ๐ฏ Atomic - Transfer fails if any check fails
Automatic tracking and enforcement:
account.Withdraw(amount, "ATM")
.Ensure(acc => acc.GetDailyWithdrawalTotal() + amount <= acc.DailyWithdrawalLimit,
Error.Validation($"Daily limit ${acc.DailyWithdrawalLimit} exceeded"))How it works:
- Tracks all withdrawals for current day
- Resets at midnight
- Configurable per account type
- Different limits for Checking vs Savings
Controlled negative balance with limits:
account.Withdraw(amount, "Emergency")
.Ensure(acc => acc.Balance - amount >= -acc.OverdraftLimit,
Error.Validation($"Overdraft limit ${acc.OverdraftLimit} exceeded"))Rules:
- โ Checking: $500 overdraft allowed
- โ Savings: No overdraft (must maintain positive balance)
- โ Money Market: $1,000 overdraft with fee
Enterprise-grade security patterns:
graph LR
A[Transaction] --> B{MFA Required?}
B -->|Yes| C[Send Code]
C --> D{Verify}
D -->|โ
| E[Process]
D -->|โ| F[Deny]
B -->|No| G{Pattern Check}
G -->|Suspicious| H[Flag for Review]
G -->|Normal| E
style E fill:#90EE90
style F fill:#FFB6C6
style H fill:#FFD700
Security Layers:
- Multi-Factor Authentication - For large transactions
- Behavioral Analysis - Pattern detection
- Real-time Monitoring - High-frequency alerts
- Automatic Freeze - Suspicious activity response
- Audit Trail - Complete transaction history
graph TB
subgraph Checking["๐ต Checking Account"]
C1[Daily Limit: $2,000]
C2[Overdraft: $500]
C3[No Interest]
C4[Unlimited Transactions]
end
subgraph Savings["๐ฐ Savings Account"]
S1[Daily Limit: $1,000]
S2[No Overdraft]
S3[Interest: 2% APY]
S4[6 Withdrawals/Month]
end
subgraph MoneyMarket["๐ Money Market"]
M1[Daily Limit: $5,000]
M2[Overdraft: $1,000]
M3[Interest: 3% APY]
M4[Min Balance: $2,500]
end
style Checking fill:#E1F5FF
style Savings fill:#90EE90
style MoneyMarket fill:#FFD700
| Validation | Rule | Error Type |
|---|---|---|
| Amount | Must be > $0 | ValidationError |
| Account Status | Must be Active | DomainError |
| Daily Limit | Total โค daily limit | ValidationError |
| Balance | Balance - amount โฅ -overdraft | ValidationError |
| Fraud Check | Must pass all fraud rules | ForbiddenError |
| MFA | Required if amount > $1,000 | UnauthorizedError |
pie title Transaction Risk Levels
"Low Risk (<$1,000)" : 70
"Medium Risk ($1,000-$5,000)" : 20
"High Risk (>$5,000)" : 10
Risk Actions:
- ๐ข Low Risk: Automatic approval
- ๐ก Medium Risk: MFA required
- ๐ด High Risk: Manual review + MFA
| # | Example | What It Demonstrates | Security Features |
|---|---|---|---|
| 1๏ธโฃ | Basic Operations | Deposits, withdrawals, domain events | โ Balance validation |
| 2๏ธโฃ | Account Transfer | Transfer between accounts | โ Parallel fraud checks |
| 3๏ธโฃ | Fraud Detection | Blocking suspicious transactions | โ Pattern detection, auto-freeze |
| 4๏ธโฃ | Daily Limits | Enforcement of withdrawal limits | โ Limit tracking, denial |
| 5๏ธโฃ | Interest Payment | Calculating and applying interest | โ Rate validation |
| 6๏ธโฃ | Domain Events | Event sourcing and change tracking | โ Audit trail |
await BankingExamples.RunExamplesAsync();Expected Output:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Example 1: Basic Account Operations โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Account created: CHK-12345
Deposited: $1,500.00
Withdrawn: $200.00
Balance: $1,300.00
Domain Events: 3
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Example 2: Account Transfer โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Transfer from CHK-12345 to SAV-67890
Amount: $500.00
Fraud Check (From): โ
Passed
Fraud Check (To): โ
Passed
Transfer Complete!
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Example 3: Fraud Detection ๐จ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Large withdrawal attempted: $7,500.00
โ ๏ธ FRAUD DETECTED: Amount exceeds threshold
Account Status: FROZEN
Security Team Notified: โ
... (continues for all 6 examples)
| Concept | What You Learn | Real-World Application |
|---|---|---|
| ๐ Security-First | Build fraud detection into domain logic | Banking, finance, payments |
| โ๏ธ Business Rules | Enforce complex rules with types | Regulatory compliance |
| ๐ Error Recovery | Automatic rollback on security issues | Fraud prevention systems |
| ๐ Parallel Operations | Concurrent validation for performance | High-volume transactions |
| ๐ก Event Sourcing | Complete audit trail via events | Regulatory reporting |
| ๐ฏ Pattern Detection | Identify suspicious behavior | Anti-money laundering |
| ๐ฐ Precision | Money type prevents rounding errors | Financial calculations |
# Navigate to example directory
cd Examples/BankingExample
# Run all 6 examples
dotnet run-
Set Startup Project
- Right-click
BankingExamplein Solution Explorer - Select "Set as Startup Project"
- Right-click
-
Run
- Press
F5(Debug) orCtrl+F5(Run without debugging) - Watch console output with security alerts
- Press
Edit Program.cs:
using BankingExample;
// Run all examples
await BankingExamples.RunExamplesAsync();
// OR run individual examples
await BankingExamples.Example1_BasicAccountOperations();
await BankingExamples.Example2_TransferBetweenAccounts();
await BankingExamples.Example3_FraudDetection();
await BankingExamples.Example4_DailyWithdrawalLimit();
await BankingExamples.Example5_InterestPayment();
await BankingExamples.Example6_DomainEventsAndChangeTracking();graph LR
A[๐ Read This README] --> B[โถ๏ธ Run Examples]
B --> C[๐ Study Security Code]
C --> D{Comfortable?}
D -->|No| E[๐ Review Fraud Detection]
E --> F[๐ Explore Patterns]
F --> B
D -->|Yes| G[๐ Try E-Commerce Example]
G --> H[๐ฏ Build Your Own]
style A fill:#E1F5FF
style B fill:#90EE90
style C fill:#FFF4E1
style G fill:#FFE1F5
style H fill:#FFB6C6
-
Start Here โ Read this README thoroughly
-
Run Examples โ Execute
dotnet runand observe security features -
Study Code โ Open files in this order:
ValueObjects/Money.cs- Precision arithmeticAggregates/BankAccount.cs- Account logic & rulesServices/FraudDetectionService.cs- Security patternsWorkflows/BankingWorkflow.cs- OrchestrationBankingExamples.cs- See it all working
-
Compare โ Check E-Commerce Example for different domain
-
Extend โ Add features (see Extensions below)
Consider implementing these features to practice:
| Feature | Complexity | What You'd Learn |
|---|---|---|
| Account Statements | โญโญ | Reporting, date ranges |
| Standing Orders | โญโญโญ | Recurring transactions, scheduling |
| Multiple Currencies | โญโญโญโญ | Foreign exchange, conversion rates |
| Joint Accounts | โญโญโญ | Multiple owners, authorization |
| Transaction Categories | โญโญ | Categorization, budgeting |
| Credit Cards | โญโญโญโญโญ | Credit limits, interest, payments |
| Loan Accounts | โญโญโญโญ | Amortization, payment schedules |
- ๐ E-Commerce - Payment processing, order workflows
- ๐ QUICKSTART.md - Choose your learning path
- ๐ Examples Overview - All examples with complexity ratings
- Error Handling - Security errors, forbidden, unauthorized
- Advanced Features - Parallel operations
- Performance - Benchmarks and optimization
After completing this example:
โ
You understand advanced security patterns
โ
You can implement fraud detection
โ
You know parallel validation techniques
โ
You've built a domain-rich aggregate
โ
You understand event sourcing for audit trails
Now try:
- ๐ E-Commerce Example for payment workflows
- ๐ Web API Examples for HTTP integration
- ๐ Clean Architecture for app structure
Questions? Check the main documentation or open an issue on GitHub.