AWS Builder Center
Building a WhatsApp-Native Payment File Orchestrator with AWS Lambda, DynamoDB, and S3

Building a WhatsApp-Native Payment File Orchestrator with AWS Lambda, DynamoDB, and S3

A serverless system that converts natural language WhatsApp messages into bank-ready HDFC CNET payment files using Lambda, DynamoDB, and S3. Covers multi-bot routing on a single WhatsApp number, DynamoDB session state design, regex-based NLP extraction for Indian payment formats, S3 presigned URLs for file delivery, and human-in-the-loop CA approval via SNS — all running at $2/month for 500 payments.

Series: WhatsApp AI Automation on AWS (1 article)

  1. 1
    Building a WhatsApp-Native Payment File Orchestrator with AWS Lambda, DynamoDB, and S3 This article
Keep on Building ;D
In India's financial ecosystem, Chartered Accountants (CAs) process hundreds of payments daily through bank portals like HDFC's CNET system. The workflow is manual: receive payment instructions via email or WhatsApp, manually format data into strict bank-specific CSV formats, upload to the portal, and authorize with OTP.
This article walks through how I built a production-grade, serverless payment orchestrator that accepts natural language payment instructions via WhatsApp and produces bank-ready payment files — using AWS Lambda for compute, DynamoDB for state management, S3 for file storage, and SNS for human-in-the-loop approval notifications.
The system has been running in production (account 008714537357, eu-central-1) since July 2026, processing real payment batches through HDFC Bank's CNET portal.



Architecture Overview

The system follows an event-driven, serverless architecture with three Lambda functions in a chain:
┌─────────────────────────────────────────────────────────────────────────┐
│ │
│ Twilio (WhatsApp) │
│ │ │
│ ▼ │
│ API Gateway (REST) ─── POST /webhook │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────┐ │
│ │ Lambda: whatsapp-router (256MB, 30s) │ │
│ │ • Parse Twilio form-urlencoded body │ │
│ │ • Keyword-based intent detection │ │
│ │ • Session-aware routing │ │
│ └─────┬──────────────────────┬───────────┘ │
│ │ Payment intent │ Default │
│ ▼ ▼ │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Lambda: │ │ Lambda: │ │
│ │ payment- │ │ MyCAAssistant-EU │ │
│ │ orchestrator │ │ (Insurance bot) │ │
│ │ (512MB, 60s) │ │ │ │
│ └────────┬──────────┘ └──────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ payment_tools.py (bundled in orchestrator package) │ │
│ │ │ │
│ │ collect_payment() → DynamoDB (payment-transactions) │ │
│ │ consolidate() → DynamoDB (payment-challans) │ │
│ │ generate_cnet_csv() → S3 (payment-files bucket) │ │
│ │ request_ca_approval()→ SNS + DynamoDB (payment-approvals)│ │
│ │ process_approval() → DynamoDB (status updates) │ │
│ │ check_status() → DynamoDB (read) │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘

Design Decisions

Why three separate Lambda functions instead of one?
  1. Router (256MB, 30s) — Lightweight, fast. Only parses the message and routes. Keeps cold start minimal for the common path (most messages go to FinBot, not payments).
  1. Orchestrator (512MB, 60s) — Heavier. Manages session state, intent detection, parameter extraction, and coordinates tool calls. Needs more memory for regex processing and DynamoDB operations.
  1. Tools are bundled with the orchestrator (not a separate Lambda) — Avoids the latency of an additional Lambda invocation. The tools are pure functions; they share the orchestrator's boto3 clients.
Why DynamoDB over ElastiCache for session state?
Sessions span hours (CA might approve next morning). DynamoDB with TTL gives durable, serverless state without managing cache clusters. PAY_PER_REQUEST billing means zero cost when idle.



Deep Dive: Multi-Bot Routing on a Single WhatsApp Number

One of the non-obvious challenges: the same WhatsApp number (Twilio) serves two completely different bots — an insurance advisor (FinBot) and this payment system.

The Routing Problem

Without routing, every message goes to one bot. We need to:
  1. Detect payment intent from natural language
  1. Maintain routing affinity during multi-turn payment flows
  1. Default to the existing bot for everything else (zero disruption)

The Solution: Keyword Detection + Session-Aware Routing

# router_lambda.py — routing logic

PAYMENT_TRIGGERS = [
# Direct payment keywords
"pay ", "pay to", "payment", "neft", "rtgs",
# CNET workflow keywords
"consolidate", "generate csv", "cnet", "batch",
"send for approval", "ca approval",
# Payment IDs (always route to payment)
"ent-", "batch-", "apr-",
]

PAYMENT_SESSION_REPLIES = [
"yes", "confirm", "proceed", "cancel", "no",
"consolidate", "generate csv", "send", "ok",
]

def should_route_to_payment(message: str, phone: str) -\> bool:
msg = message.lower().strip()

# Check keywords
for trigger in PAYMENT_TRIGGERS:
if trigger in msg:
return True

# Check payment IDs (regex)
if re.search(r"(ent|apr|batch|chn|pay)-\w+", msg, re.IGNORECASE):
return True

# Session affinity: if user is mid-payment-flow, short replies stay in payment
if msg in PAYMENT_SESSION_REPLIES and has_active_payment_session(phone):
return True

return False

Session Detection via DynamoDB

def has_active_payment_session(phone: str) -\> bool:
"""Check DynamoDB for active payment session."""
resp = chat_table.get_item(
Key={"phone": f"SESSION_{phone}", "timestamp": "0"}
)
item = resp.get("Item")
if item and int(item.get("ttl", 0)) \> int(time.time()):
state = json.loads(item.get("state", "{}"))
return bool(state.get("step"))
return False
This uses a single-item DynamoDB read (fast, <5ms) to check if the user has an active payment flow. The TTL ensures stale sessions don't cause permanent routing affinity.
Lesson learned: I initially missed keywords like "consolidate" and "generate csv" in the trigger list. Result: "Consolidate" routed to the insurance bot, which responded in German about financial consolidation advice. Fixed by adding all CNET workflow terms to the trigger list.



Deep Dive: Stateful Conversational Flows with DynamoDB

Payment workflows are inherently multi-turn. A user collects 5 payments across 5 messages before consolidating. The orchestrator needs to remember what was collected.

Session State Design

Table: payment-chat-history
PK: SESSION_{phone_number}
SK: 0 (fixed — one session per user)
TTL: current_time + 7200 (2 hours)

State JSON:
{
"step": "collecting|consolidated|csv_generated|awaiting_ca_approval",
"collected_ids": ["ENT-20260727-BB7A9E", "ENT-20260727-8C6E57"],
"batch_id": "BATCH-20260727-DD8998",
"total_amount": 100000,
"entry_count": 2,
"file_name": "CNET_Batch-20260727-0904_20260727_090500.csv",
"download_url": "https://s3.eu-central-1.amazonaws.com/...",
"approval_id": "APR-20260727-9501E2"
}

Why This Works for Lambda

  • Stateless compute: Lambda doesn't maintain state between invocations. Every message is a fresh invocation that reads state from DynamoDB.
  • Atomic updates:  put_item  with the full state object ensures consistency (no partial updates).
  • Auto-cleanup: TTL removes stale sessions automatically. No cron jobs, no garbage collection.
  • Cost: Single-digit millisecond reads/writes. PAY_PER_REQUEST means zero cost between payment batches.

State Machine

[New User] ──────────────────────────────────────────────────────┐
│ │
▼ (sends payment details) │
[collecting] ◄──── (add more) ────┐ │
│ │ │
▼ ("consolidate") │ │
[consolidated] ───────────────────┘ │
│ │
▼ ("generate csv") │
[csv_generated] │
│ │
▼ ("send for approval") │
[awaiting_ca_approval] │
│ │
▼ (CA: "APPROVE APR-xxx") │
[DONE] ── clear_session() ─────────────────────────────────────┘



Deep Dive: Generating Bank-Compliant Payment Files with S3

The HDFC CNET format has strict requirements that catch most people off-guard:
Field
Constraint
Why It Matters
Party Name
Max 14 characters
Bank verification API rejects longer names silently
Account Number
Text, not integer
Leading zeros (00123456) get stripped if stored as number
Date
dd/mm/yyyy exactly
Any other format = batch rejection
Bank Code
N, M, or I only
N=NEFT, M=RTGS, I=HDFC internal
Amount
2 decimal places
50000 must be written as 50000.00

CSV Generation with S3

def generate_cnet_csv(params: dict) -\> dict:
batch_id = params.get("batch_id")

# Fetch batch from DynamoDB
batch = challans_table.get_item(Key={"challanId": batch_id})
entries = json.loads(batch["Item"]["entries"])

# Generate CSV in memory
csv_buffer = io.StringIO()
writer = csv.writer(csv_buffer)

# Header
writer.writerow([
"Bank Code", "Serial No", "Account Number",
"Party Name", "Amount", "Date",
"IFSC Code", "Bank Name", "Mail Reference",
])

# Data rows — enforce all constraints
for entry in entries:
writer.writerow([
entry["bank_code"], # N/M/I
entry["serial_no"], # Sequential
entry["account_number"], # Text (leading zeros safe)
entry["party_name"][:14], # Enforce 14 char limit
f"{entry['amount']:.2f}", # 2 decimal places
entry["date"], # dd/mm/yyyy
entry["ifsc_code"], # 11-char IFSC
entry["bank_name"], # Free text
entry["mail_reference"], # Invoice ref
])

# Upload to S3 with metadata
s3_key = f"cnet-files/{datetime.now().strftime('%Y/%m')}/{file_name}"
s3.put_object(
Bucket="payment-files-008714537357",
Key=s3_key,
Body=csv_buffer.getvalue().encode("utf-8"),
ContentType="text/csv",
Metadata={
"batch_id": batch_id,
"entry_count": str(len(entries)),
"total_amount": str(total_amount),
},
)

# Generate presigned URL (24h expiry)
download_url = s3.generate_presigned_url(
"get_object",
Params={"Bucket": BUCKET, "Key": s3_key},
ExpiresIn=86400,
)

return {"file_name": file_name, "download_url": download_url}

S3 Design Choices

  • Prefix structure:  cnet-files/2026/07/filename.csv  — enables lifecycle policies per month
  • Presigned URLs: CA gets a download link valid for 24 hours. No bucket policy changes needed.
  • Object metadata: batch_id, entry_count, total_amount stored as S3 metadata for quick lookups without reading the file
  • No public access: Bucket is private. Only presigned URLs grant temporary read access.



Deep Dive: Human-in-the-Loop Approval with SNS

Payments require authorized approval. The system uses SNS to bridge the gap between automated file generation and human authorization.

Approval Flow

def request_ca_approval(params: dict) -\> dict:
approval_id = f"APR-{datetime.now().strftime('%Y%m%d')}-{uuid4()[:6].upper()}"

# Store approval request in DynamoDB
approvals_table.put_item(Item={
"approvalId": approval_id,
"batchId": params["batch_id"],
"status": "PENDING",
"totalAmount": Decimal(str(params["total_amount"])),
"fileName": params["file_name"],
"downloadUrl": params["download_url"],
"requestedAt": int(time.time()),
"ttl": int(time.time()) + 86400 * 90, # 90-day retention
})

# Notify CA via SNS
notification = (
f"CNET Payment File Ready for Upload\n\n"
f"Approval ID: {approval_id}\n"
f"File: {params['file_name']}\n"
f"Total: INR {params['total_amount']:,.2f}\n"
f"Entries: {params['entry_count']}\n\n"
f"Action: Download → HDFC CNET → Upload → OTP → Reply APPROVE {approval_id}"
)

sns.publish(
TopicArn=SNS_TOPIC_ARN,
Message=notification,
Subject=f"CNET Upload: INR {params['total_amount']:,.2f}",
)

return {"approval_id": approval_id, "status": "PENDING"}

Why SNS Over Direct WhatsApp?

  1. Multi-channel delivery: SNS can deliver to email, SMS, and other endpoints. CA might prefer email for the download link.
  1. Decoupled: If WhatsApp delivery fails, the notification still reaches the CA via email.
  1. Audit: SNS delivery status is logged in CloudWatch automatically.
  1. Fan-out: Multiple CAs can subscribe to the same topic (e.g., primary + backup approver).

Approval Response via WhatsApp

The CA replies on WhatsApp:  "APPROVE APR-20260727-9501E2" 
The router detects the  apr-  pattern, routes to the payment orchestrator, which updates DynamoDB:
def process_approval_response(approval_id: str, decision: str, approved_by: str):
approvals_table.update_item(
Key={"approvalId": approval_id},
UpdateExpression="SET #s = :status, approvedAt = :at, approvedBy = :by",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={
":status": "APPROVED", # or REJECTED/ON_HOLD
":at": int(time.time()),
":by": approved_by,
},
)

# Update batch to PAYMENT_COMPLETE
challans_table.update_item(
Key={"challanId": batch_id},
UpdateExpression="SET #s = :status, paidAt = :at",
ExpressionAttributeValues={":status": "PAYMENT_COMPLETE", ":at": int(time.time())},
)



Natural Language Processing Without LLMs

A deliberate design choice: the NLP layer uses regex-based extraction instead of Bedrock/LLM calls.

Why Regex Over Bedrock?

Factor
Regex
LLM (Bedrock)
Latency
<1ms
500-2000ms
Cost
$0
$0.001-0.01 per call
Determinism
100% reproducible
Probabilistic
Cold start impact
None
Model loading
Indian formats
Custom patterns
Needs fine-tuning
For structured extraction (amounts, IFSC codes, account numbers), regex is faster, cheaper, and more reliable than an LLM call.

Extraction Examples

# Indian amount formats: ₹1,00,000 / 1 lakh / 2 crore / 75k
amt_match = re.search(r"[₹$€£]?\s*([\d,]+\.?\d*)\s*(lakh|lac|k|crore|cr)?", msg)

# IFSC code: exactly 4 letters + 0 + 6 alphanumeric
ifsc_match = re.search(r"\b([A-Z]{4}0[A-Z0-9]{6})\b", msg, re.IGNORECASE)

# Auto-detect bank from IFSC prefix
bank_map = {"HDFC": "HDFC Bank", "SBIN": "State Bank of India", "ICIC": "ICICI Bank"}

# Account number: 8-18 digits near "acc" keyword
acc_match = re.search(r"(?:acc(?:ount)?\.?\s*[:=]?\s*)(\d{8,18})", msg)



Infrastructure as Code

All DynamoDB tables deployed via CloudFormation:
Resources:
TransactionsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: payment-transactions
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: transactionId
AttributeType: S
KeySchema:
- AttributeName: transactionId
KeyType: HASH
TimeToLiveSpecification:
AttributeName: ttl
Enabled: true
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: true
Key IaC decisions:
  • PAY_PER_REQUEST — No capacity planning. Scales to zero when idle.
  • TTL on all tables — Automatic cleanup. No manual purging.
  • PITR enabled — 35-day point-in-time recovery for compliance (payment data).



Cost Analysis

For a typical CA processing 500 payments/month:
Service
Usage
Monthly Cost
Lambda
~1500 invocations (3 per payment)
$0.03
DynamoDB
~3000 reads + 2000 writes
$1.25
S3
~50 CSV files (avg 2KB)
$0.01
SNS
~50 notifications
$0.03
API Gateway
~500 requests
$0.50
Total

~$2/month
At 5000 payments/month (10 CA clients): ~$15/month.
The serverless model means costs scale linearly with usage. Zero traffic = zero cost (except S3 storage, which is negligible).



Lessons Learned

1. Bank Format Strictness is Unforgiving

HDFC CNET rejects the entire batch if one party name is 15 characters. Not a warning — a silent rejection. Always truncate at the application layer, never trust user input.

2. Leading Zeros Are a Data Type Problem

Account number  00123456789  becomes  123456789  if stored as a number. Always store as string/text in DynamoDB. Always write as text in CSV.

3. Multi-Bot Routing Needs Session Awareness

Keyword-only routing fails for short replies ("yes", "ok", "consolidate"). You need session state to maintain routing affinity during multi-turn flows.

4. Presigned URLs > Inline File Content

WhatsApp has message length limits. Sending a CSV inline doesn't work for large batches. Presigned URLs let the CA download the file in any browser/app.

5. Regex Beats LLMs for Structured Extraction

When the input format is semi-structured (IFSC codes, account numbers, amounts), regex is 1000x faster, free, and deterministic. Save LLM budget for ambiguous tasks.



Extending to Other Bank Formats

The architecture is designed as a plugin system. The orchestrator and consolidation logic remain unchanged — only the output adapter changes:
# Format adapter pattern
def generate_payment_file(batch, format_type):
adapters = {
"hdfc_cnet": generate_cnet_csv, # India - HDFC
"sepa_xml": generate_sepa_pain001, # EU - SEPA
"bacs_csv": generate_bacs_csv, # UK - BACS
"ach_nacha": generate_nacha_file, # US - ACH
}
return adapters[format_type](batch)
Each adapter implements the same interface: takes a batch of entries, returns a formatted file. The WhatsApp interface, session management, and approval workflow are completely reusable.



Conclusion

This project demonstrates that serverless AWS services are production-ready for financial workflows:
  • Lambda handles burst traffic (Monday morning payment batches) without provisioning
  • DynamoDB provides single-digit-millisecond session state at any scale
  • S3 delivers secure, temporary file access without managing download servers
  • SNS bridges automated systems with human approval gates
The total cost for a production financial system: under $10/month. The value delivered: 20+ hours saved per CA per month with zero format errors.
The code is structured for multi-tenant SaaS expansion — same WhatsApp interface, pluggable bank format adapters, per-tenant configuration in DynamoDB.



Resources



Saurabh Mukherjee is a serverless and GenAI practitioner building production AI systems on AWS. He specializes in event-driven architectures, Bedrock-powered agents, and WhatsApp-native automation for financial services.

Series: WhatsApp AI Automation on AWS (1 article)

  1. 1
    Building a WhatsApp-Native Payment File Orchestrator with AWS Lambda, DynamoDB, and S3 This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article