Skip to main content

Scenario: AWS Enterprise File Transfer

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

Source: Interview framing from LinkedIn — Designing a Secure Enterprise File-Transfer Platform with AWS (Himanshu Bhadra).

Five pillars (interview + game day): Idempotency · Duplicates · Replay · DR switch · Back-of-envelope 1M/day

1. The Interview Question​

"How would you design a secure enterprise file-transfer platform capable of processing up to one million files per day?"

Principal signal: Do not start by listing AWS services. Clarify requirements first—then defend architecture trade-offs.

Step-by-step flow:

StepActionExplanation
1ClarifyPartners, protocols, sizes, SLAs, DR, security—before any AWS list
2–3Scope + TopologyBound the problem, then draw ingress → storage → orchestration
4–5Trade-offs + failuresBackpressure, idempotency, large files, poison messages
6EvolvePhased delivery that interviewers can probe

2. Real-World Context​

DimensionDetail
Company / systemEnterprise managed file transfer (MFT) / B2B exchange on AWS
ScaleUp to 1M files/day (~12 files/sec average; bursts much higher); mixed small EDI and multi-GB batches
Why architects carePartner SLAs, compliance audit trails, idempotent delivery, multi-protocol ingress, and DR—not "upload to S3"
Deep chapterGlobal File Transfer Platform
Public referencesAWS Transfer Family; S3 event notifications; Step Functions orchestration

Clarifying questions (ask before designing)​

AreaQuestions
TopologyHow many source/target systems? Internal only or external partners?
ProtocolsSFTP, FTPS, AS2, HTTPS API, S3-compatible?
PayloadFile-size ranges? Max object size? Compression / encryption in transit?
TimingReal-time, scheduled windows, or event-driven? Peak hours?
DRRTO / RPO? Multi-region required?
CorrectnessDuplicate files? Partial transfers? Exactly-once business effect?
SecurityTenant isolation, PII, audit, retention, data residency?
OpsOnboarding automation? Failed-transfer detection, retry, reconcile?

3. Step-by-Step Interview Answer (STEP)​

Practice aloud with the STEP framework.

S — Scope​

DecisionChoice
Throughput1M files/day sustained; design for 10× burst on partner windows
DurabilityS3 as blob store (11 nines in-region); metadata in DynamoDB
DeliveryAt-least-once with idempotent completion (checksum + transfer_id)
SecurityEncryption in transit/at rest; per-tenant IAM / logical isolation
Out of scope (unless asked)Full AS2 EDI mapping product; desktop sync client

Step-by-step flow:

StepChoiceWhy
1In scopePlatform concerns: ingress, durability, orchestration, correctness, ops
2Out of scopeProduct surface area that distracts from architecture interview

T — Topology (AWS reference architecture)​

Step-by-step flow:

StepActionExplanation
1–2IngressTransfer Family for managed SFTP; API Gateway for programmatic/HTTPS uploads
3–4Persist blobLand in S3 with SSE-KMS; never process only from ephemeral disk
5–6EventS3 → EventBridge → SQS for backpressure
7–8OrchestrateStep Functions + Lambda: schema/checksum, malware hook, routing rules
9StateDynamoDB holds transfer_id, checksum, status, partner_id (idempotency)
10CompleteMove/copy to processed prefix or push to target; mark SUCCEEDED once

Happy-path sequence (whiteboard story)​

Step-by-step flow:

StepActionExplanation
1–2Upload + landBlob hits durable S3 before any business processing
3–5DecoupleEvents + queue absorb partner upload bursts
6–7Validate + claimChecksum/scan then claim work with conditional write
8–9Route or no-opFirst writer delivers; duplicates return prior success
10CloseMetrics for SLA dashboards

Transfer lifecycle state machine​

Step-by-step flow:

StepState transitionExplanation
1–2RECEIVED → VALIDATINGControl plane owns status; blob stays in S3
3BranchFail closed to quarantine; never fail-open malware
4–5Route / retryAt-least-once delivery with idempotent SUCCEEDED
6–7TerminalQuarantine needs humans; SUCCESS is durable

E — Explore trade-offs (defend these)​

TopicStrong stance
Scalability / backpressureSQS + concurrency limits; never unbounded Lambda fan-out on 1M/day spikes
Large filesMultipart upload; resumable; process via S3-native jobs—not load entire object into Lambda memory
IdempotencyKey = partner + remote_name + checksum (or client transfer_id); DynamoDB conditional writes
Security / tenantsSeparate IAM roles / prefixes per partner; KMS CMKs; Secrets Manager for credentials; VPC endpoints
Retry / replayStep Functions retries + DLQ; operator replay from failed state without re-charging partners
ObservabilityTransfer state machine metrics; age-of-oldest-pending; partner SLA dashboards
Multi-regionCRR on critical buckets + active/passive control plane; document RPO/RTO
Cost vs complexityTransfer Family + managed services beat DIY SFTP fleets for most enterprises

Backpressure at peak (1M/day ≠ flat rate)​

Step-by-step flow:

StepActionExplanation
1–2Land + queueStorage and SQS absorb spikes; partners are not gated on CPU
3Concurrency capsProtect downstream targets and Lambda memory
4DLQIsolate poison files without stalling the queue

Small vs large file paths​

Step-by-step flow:

StepPathExplanation
1Size gateSame control plane; different data plane
2a / 3aSmallLambda OK for KB–MB EDI
2b / 3bLargeNever load GB into Lambda; stream or Step Functions + ECS/Batch
4CompleteBoth paths write the same idempotent SUCCEEDED record

Idempotency key (duplicate same day)​

Step-by-step flow:

StepActionExplanation
1–2ClaimFirst writer owns delivery
3–4ConflictSecond writer loses race safely
5–6Deliver onceBusiness effect happens once
7–8Safe ackDuplicate upload does not double-route

Tenant isolation & security plane​

Step-by-step flow:

StepActionExplanation
1–3Partner A pathDedicated identity, prefix, and CMK
4–6Partner B pathSame pattern; no shared write role
7IsolationCross-prefix denied by IAM
8–9SecretsCredentials never in Lambda env plain text
AuditCloudTrail / CWWho uploaded what, when

P — Production failure modes​

FailureDetectionMitigation
Partial SFTP uploadIncomplete multipart / size mismatchRequire checksum; quarantine incomplete
Duplicate file same daySame idempotency keyReturn prior success; no double-route
Virus / malwareScanner hook fails open?Fail closed to quarantine prefix
Partner cert expiryAuth failures spikeCert inventory + rotation runbook
Poison messageDLQ depthAlert; manual replay tooling
Region outageHealth + R53Failover runbook; CRR lag as RPO floor

Step-by-step flow:

StepActionExplanation
1–2ClassifySuccess vs retryable vs security reject
3–4DLQ + alertDo not block healthy partners
5–6Replay / reviewOperator tools without re-billing partners

Evolve — roadmap​

PhaseDeliverable
M1Transfer Family + S3 landing + DynamoDB state + basic validate
M2EventBridge/SQS/Step Functions; DLQ + replay UI
M3Tenant isolation, KMS, audit export for compliance
M4Multi-region DR drill; partner self-service onboarding
M5Cost dashboards; lifecycle tiering for cold files

4. Back-of-envelope numbers (1M transfers/day)​

Interviewers expect you to show the math, then design for peak, not average.

4.1 Throughput​

AssumptionValueMath
Daily volume1,000,000 transfers/dayGiven
Seconds/day86,400—
Average rate≈ 11.6 ≈ 12 transfers/s1e6 / 86400
Partner window (common)4 hours overnight14,400 s
If 60% of volume in window600,000 / 14,400≈ 42 transfers/s sustained in window
Burst (2× window rate)Design target≈ 80–100 transfers/s
Extreme spike (retail EDI)10–20× average120–240 transfers/s for minutes

Step-by-step flow:

StepSay in interviewImplication
1“~12/s average is easy”S3 + DDB on-demand handle this cold
2“Real load is the SLA window”Queues exist for a reason
3“Design ~100/s ingest+validate”Not 12/s
4“Cap compute; let SQS absorb”Protect downstream

4.2 Object size mix (capacity drivers)​

TierShare (example)SizeBytes/dayNotes
Small EDI / XML70% = 700k50 KB avg~35 GB/dayLambda OK
Medium25% = 250k5 MB avg~1.25 TB/dayMultipart; careful Lambda
Large batch5% = 50k500 MB avg~25 TB/dayECS/Batch only
Total storage/day~26.3 TB/day landingBefore lifecycle

Interview line: “Count files and bytes separately—1M tiny files stresses metadata/orchestration; GB files stress bandwidth and memory.”

4.3 Control-plane ops (DynamoDB / queues)​

ResourceOps estimateCapacity note
DDB writes / transfer~5–8 (create, claim, validate, route, succeed, audit)5–8M WRU/day ≈ 60–90 WRU/s avg; 400–800/s at peak
DDB readsStatus API + idempotency lookupOn-demand or provisioned with burst
SQS sends1–2 per transfer~12–100 msg/s — well under SQS limits
Step Functions starts1 per transfer (or batch Map)Watch OpenExecution quota; raise limit
Lambda concurrent (validate)rate × duratione.g. 100/s × 2s = 200 concurrent → set reserved concurrency
S3 PUT≥1 per transfer (+ multipart parts)Partition keys by partner/date

4.4 Network & cost sketch (order of magnitude)​

ItemRough mathTalk track
Ingress bandwidth (26 TB/day)26e12 B / 86400 ≈ ~2.4 Gbps average; window higherSize Transfer Family / NLB accordingly
Cross-AZ / same-regionPrefer same-region landAvoid surprise egress
DDB on-demandCents per million WRU at this scaleMetadata is cheap vs bytes
Lambda1M × 2s × 1GB ≈ 2M GB-s/dayRoute large files off Lambda
S3 storage growth26 TB/day raw → lifecycle mandatoryIA / expire landing

4.5 What to write on the whiteboard​

1M/day → 12/s avg → design 100/s peak
Bytes: ~25–30 TB/day (mix matters)
DDB: ~5–8 writes/transfer → hundreds WRU/s peak
Lambda concurrency ≈ rate × p95 latency
SQS depth = shock absorber; DLQ = poison isolation
RPO = CRR lag; RTO = runbook clock (game day)
MetricRough math
Average rate1e6 / 86400 ≈ 12 files/s
Peak design~80–100 files/s (window + headroom)
Metadata5–8M DDB writes/day — fine on-demand
Hot path riskLambda memory on large files — size gate
BackpressureSQS depth + Step Functions / Lambda concurrency caps

5. Multi-region DR sketch​

Step-by-step flow:

StepActionExplanation
1–2Replicate data + control planeBlobs and transfer status both matter
3–5FailoverWorkers follow DNS/flag; RPO = max(CRR lag, DDB lag)

6. Whiteboard checklist​

Draw five boxes left-to-right, then annotate failure paths underneath:

  • Clarifying questions before AWS shopping list
  • Ingress protocols called out
  • Blob vs metadata separation (S3 + DynamoDB)
  • Idempotency key defined
  • Queue + DLQ for failure
  • Security: KMS, IAM, Secrets, tenant isolation
  • Observability: pending age, success/fail by partner
  • DR: RPO/RTO one-liner

7. Principal-level signals​

StrongWeak / red flag
Requirements first"I'd use S3 and Lambda" immediately
Idempotency + checksumAssume SFTP is exactly-once
Backpressure designUnbounded fan-out
Tenant isolation + auditShared bucket, no KMS story
Large-file strategyLoad GB files into Lambda
Links to MFT depthTreats as toy upload API

8. Compact outline (2 minutes)​

"I'd clarify partners, protocols, sizes, SLAs, and DR first. Then: Transfer Family/API ingress → S3 + KMS → EventBridge/SQS → Step Functions validate/route → DynamoDB idempotent state → CloudWatch. Defend backpressure, large files, duplicates, security, retries, and multi-region. 1M/day is easy on average; peaks and poison files are the real design."

9. Production HLD​

9.1 C4 context​

Step-by-step flow:

StepInteractionExplanation
1Partner → PlatformMulti-protocol ingress (Transfer Family, API)
2Platform → S3Durable blob first; SSE-KMS
3WorkersChecksum, malware hook, schema, route
4MetaIdempotency, status, partner config
5TargetProcessed prefix, partner egress, or event notify
6–7Ops / ComplianceGame-day tools + immutable audit

9.2 Full production stack​

LayerAWS servicePurpose
SFTP ingressAWS Transfer Family (SFTP)Managed endpoints; custom IdP / Secrets Manager
HTTPS ingressAPI Gateway + Lambda / ECSInitiate transfer, presigned multipart, status API
Object storeS3 (versioned, SSE-KMS)landing/, quarantine/, processed/, egress/
EventsEventBridgeS3 ObjectCreated → rules by prefix/partner
BackpressureSQS (+ DLQ)Validate queue, route queue, egress queue
OrchestrationStep FunctionsDurable workflow; retries; map for batches
WorkersLambda (small) + ECS/Batch (large)Size-gated processing
StateDynamoDBTransfers, partners, idempotency, leases
SecretsSecrets ManagerPartner SSH keys, egress passwords, API keys
KeysKMS CMKs (per tenant or tier)At-rest encryption; grant to workers
ScanLambda hook → GuardDuty Malware Protection / AVFail closed → quarantine
NotifySNS / EventBridgetransfer.succeeded / transfer.failed
IaCTerraform + CI/CDEnvironments, partner onboarding modules
ObsCloudWatch + X-Ray + CloudTrailSLOs, forensics, audit
DRS3 CRR + DynamoDB Global Tables (or PITR)Regional failover

9.3 Component interaction (production)​

Step-by-step flow:

StepPathExplanation
1–2IngressSFTP or HTTPS lands object under partner prefix
3–5DecoupleEvent → queue → state machine (burst safe)
6–7BranchValid → route queue; bad → quarantine + FAILED
RouteDeliverCopy/compose to processed; emit events; SUCCEEDED once

9.4 SLOs (interview + ops contract)​

Illustrative targets for a production MFT platform. In an interview: define the SLI, show the math, name how you measure, then tie to the architecture that achieves it.

SLOTarget (illustrative)Notes
Availability (control plane)99.9% monthlyStatus + initiate APIs
Time-to-validate p95< 2 min for files ≤ 100 MBAfter ObjectCreated
Time-to-complete p95Within partner window WWindow defined per contract
Duplicate delivery rate0 business double-routesIdempotency enforced
Poison isolationDLQ depth alert < 15 min MTTAHealthy partners unaffected
RPO (regional DR)≤ 15 min critical tierS3 RTC + DDB lag
RTO (regional DR)≤ 60 minDocumented game day

9.4.1 Availability 99.9% (control plane) — how calculated​

What is in scope: POST /v1/transfers (initiate), GET /v1/transfers/{id} (status), auth to Transfer Family IdP health—not “every partner file finished.” Data-plane backlogs are latency/completeness SLOs, not this availability number.

SLI (say aloud):

[ \text{availability} = \frac{\text{successful requests}}{\text{successful} + \text{failed} + \text{timed-out}} ]

over a calendar month (exclude client 4xx except 429 from your infra; count 5xx and gateway timeouts as failed).

Error budget math (30-day month):

StepCalculationResult
1Allowed downtime fraction(1 - 0.999 = 0.001) = 0.1%
2Minutes in 30 days(30 \times 24 \times 60 = 43{,}200)
3Error budget(43{,}200 \times 0.001 =) 43.2 minutes downtime/month
4If multi-AZ API is up 99.95%Budget left ≈ 21.6 min for deploys/incidents
Interview line:
"99.9% monthly ≈ 43 minutes of allowed control-plane unavailability.
I burn that budget on incidents and risky deploys—not on silent 5xx."

How achieved (architecture):

LeverWhy it hits 99.9%
Multi-AZ API Gateway / ECS / LambdaAZ loss ≠ region outage
DynamoDB on-demand + multi-AZStatus/idempotency reads stay up
Transfer Family multi-AZ endpointSFTP control path survives AZ
No single shared “upload pod disk”Control plane doesn’t depend on local disk
Deploy with canary + rollbackProtects the 43-minute budget
Dependencies: fail soft on scanInitiate/status still answer if AV is slow

How measured: CloudWatch 4XX/5XX on API Gateway + custom success ratio; synthetic canary every 1 min (initiate dry-run or status of known transfer). Alert when burn rate would exhaust budget in < 2 days (multi-window burn).


9.4.2 Time-to-validate p95 < 2 minutes (≤ 100 MB) — how calculated​

Definition: For each transfer with bytes ≤ 100 MB:

[ T_{\text{validate}} = t(\text{status} \in {\text{VALIDATED}, \text{QUARANTINED}, \text{FAILED}}) - t(\text{ObjectCreated}) ]

p95 = 95th percentile of (T_{\text{validate}}) over a rolling window (e.g. 1 hour or 1 day)—not the average.

Latency budget breakdown (must fit under 120 s at p95):

StageTypical p95 budgetNotes
S3 → EventBridge → SQS1–5 sEventual; usually seconds
Queue waitdominant under loadCap with concurrency; alarm on depth
Lambda cold start (occasional)0.5–2 sProvisioned concurrency for validate if needed
Download/hash ≤ 100 MB1–20 sSame-region; ~50–100 MB/s effective OK
Malware scan hook5–30 sAsync or bounded; fail closed without blocking forever
DynamoDB upsert< 50 msNegligible
Sum target< 120 sLeave headroom for queue wait
Interview line:
"p95 < 2 min means 95 of 100 small files finish validate within 120s after land.
If average is 10s but p95 is 8 min, the queue is the problem—not Lambda code."

How achieved:

LeverEffect
EventBridge → SQS (not sync Lambda from S3)Smooths bursts; protects p95
Reserved concurrency on validatePredictable drain rate
Size gate: ≤100 MB on Lambda pathAvoids OOM / multi-minute downloads
Same-region S3 + workersNo cross-region GET in hot path
Scan timeout + quarantine pathBounded; doesn’t inflate success-path forever
Alarm: validate_latency_ms p95 + ApproximateAgeOfOldestMessageCatch budget burn early

BOE check at 1M/day: avg ~12/s; design ~100/s peak. If each validate takes 5 s CPU, need ~500 concurrent workers at peak—set concurrency consciously so queue wait stays inside the 2-minute p95.


9.4.3 Time-to-complete p95 within partner window W — how calculated​

Definition: Partner contract defines window (W) (example: “all files dropped by 02:00 UTC processed by 06:00 UTC” ⇒ (W = 4) hours).

[ T_{\text{complete}} = t(\text{SUCCEEDED} \lor \text{terminal FAILED}) - t(\text{RECEIVED}) ]

SLO: (P_{95}(T_{\text{complete}}) \le W) for transfers in that partner’s cohort (or: ≥95% of files in the batch complete before window end—same idea, batch framing).

Example math (say in interview):

InputValue
Nightly drop600,000 files between 22:00–02:00
Window end06:00 ⇒ W = 4 h = 14,400 s after last drop (or from window start—clarify with partner)
p95 complete target≤ 14,400 s
Required average drain if backlog = 600k at 02:00(600{,}000 / 14{,}400 \approx) 42 files/s sustained
Interview line:
"I don't promise 'fast'—I promise completion inside W. Capacity = peak backlog / W,
with headroom. 600k files / 4h ≈ 42/s—our §4 peak design of ~100/s covers that."

How achieved:

LeverEffect
SQS depth as bufferPartners land at burst; workers drain at capped rate
Separate validate vs route queuesSlow egress doesn’t block validate SLO
Autoscale on ApproximateNumberOfMessages + oldest ageProtect W
Partner-priority / weighted fair queuesOne noisy partner doesn’t miss everyone’s W
Large-file ECS pathBig objects don’t stall small-file p95
Dashboard: % complete by window deadlineBusiness-facing SLI

9.4.4 Duplicate delivery rate = 0 — how calculated​

This is a safety SLO, not a latency percentile.

SLI:

[ \text{duplicate delivery rate} = \frac{\text{business effects with same idempotency key} - 1}{\text{unique idempotency keys succeeded}} ]

Target: 0 double-routes (exactly one transfer.succeeded side effect per key). Idempotent hits (second upload returns prior success) are good, not violations.

How you “calculate” in practice:

SignalExpected
Metric idempotent_hitCan be high (retries)
Metric route_executed per idempotency_keyMust be 0 or 1
Downstream unique constraint / counterGame day: upload twice → target row count +1
Audit: two SUCCEEDED notifies same keyPage — SLO breach
Interview line:
"Zero duplicate delivery means at-most-once business effect.
We measure 'routes per idempotency key ≤ 1', not 'zero partner retries'."

How achieved: DynamoDB conditional Put on idempotency key; CAS to SUCCEEDED before notify; SF execution name = hash(key); target writes idempotent; replay blocked when already SUCCEEDED (§10A.1–10A.3).


9.4.5 Poison isolation — DLQ alert MTTA < 15 min — how calculated​

MTTA = Mean Time To Acknowledge (human or auto-ack of the incident), not MTTR.

SLI: For each period when DLQ_VisibleMessages > 0 (or depth exceeds threshold):

[ \text{time-to-ack} = t(\text{page acknowledged / IC claimed}) - t(\text{alarm firing}) ]

SLO: median or mean time-to-ack < 15 minutes (or: 95% of poison alarms acked within 15 min).

Why 15 minutes: Poison must not sit silently while operators sleep through a partner batch window; 15 min is an ops response target compatible with paging + runbook open.

Interview line:
"Isolation SLO isn't 'no poison files'—malware happens.
It's 'DLQ alarms page us and we acknowledge within 15 minutes,
while healthy partners keep draining on the main queue.'"

How achieved:

LeverEffect
Separate main queue vs DLQBad messages don’t block good ones
maxReceiveCount → DLQAutomatic isolation after N failures
CloudWatch alarm on DLQ depth > 0Fast detect
PagerDuty / SNS → on-callMTTA clock starts
Quarantine prefix for malwareSecurity path ≠ retry loop
Runbook GD-2Ack + triage without redrive to route

9.4.6 RPO ≤ 15 min (critical tier) — how calculated​

RPO = maximum acceptable data loss measured in time:

[ \text{RPO} = t_{\text{failover declare}} - t_{\text{last durable write that will be visible on DR}} ]

Practically: replication lag at failover time.

ComponentLag signalCritical-tier target
S3 objectsReplicationLatency / RTC≤ 15 min for 99.99% of objects (S3 RTC promise)
DynamoDB stateGlobal Table replication lagTypically seconds–low minutes; take max(S3, DDB)
Effective RPO(\max(\text{S3 lag}, \text{DDB lag}))
Interview line:
"RPO 15 minutes means if the region dies at 10:00, we may lose up to
15 minutes of not-yet-replicated lands/state. We buy S3 RTC on critical
prefixes and measure lag in game day—not hope."

How achieved: S3 CRR + Replication Time Control on critical landing/processed prefixes; DynamoDB Global Tables; alarm if ReplicationLatency > 900s; don’t claim RPO 0 without sync cross-region (usually too expensive).


9.4.7 RTO ≤ 60 min — how calculated​

RTO = time from declare failover until service meets minimum viable SLOs on DR (canary SUCCEEDED + partners can connect).

PhaseBudget (illustrative)Clock contribution
Detect + confirm (dual signal)0–10 minAlarms + AWS Health + IC
Set failover_mode + active_region1–2 minSSM / AppConfig
DNS / partner endpoint cutover5–15 minTTL + Transfer Family DR warm
Scale workers to prod concurrency5–15 minSF / ECS
Canary upload + status + reconcile sweep10–15 minProve correctness
Total target≤ 60 minSum of phases + buffer
Interview line:
"RTO 60 minutes is a runbook clock, not a marketing slide.
We game-day GD-8 quarterly and publish actual T+ times.
Untested RTO is fiction."

How achieved: Warm/pilot Transfer Family in DR; SSM flags before DNS; CRR already warm; documented GD-8; synthetic canary; in-flight sweeper (S3 list + DDB)—see §10A.4.


9.4.8 Interview cheat sheet — one board​

99.9% avail → 43 min/month error budget (control plane APIs)
p95 validate → ObjectCreated → VALIDATED; budget stages < 120s; queue is p95 killer
p95 complete → backlog/W drain rate; e.g. 600k/4h ≈ 42/s
dup delivery=0 → routes per idempotency_key ≤ 1 (retries OK)
poison MTTA → DLQ alarm → ack < 15 min; main queue keeps draining
RPO ≤ 15 min → max(S3 RTC lag, DDB lag) at failover
RTO ≤ 60 min → sum of detect→flags→DNS→scale→canary (game day)
Student trapStrong recovery
“99.9% means files always finish”Separate API availability vs completion latency
“Average validate is 5 s so SLO is fine”Use p95/p99, not mean
“RPO/RTO are the same”RPO = data loss; RTO = time to restore service
“Zero duplicates = no retries”Retries expected; zero double business effects
“We’ll failover instantly”Show phased RTO budget + game day

10. Production Low-Level Design​

10.1 S3 key layout​

s3://mft-prod-{region}/
landing/{partner_id}/{yyyy}/{mm}/{dd}/{transfer_id}/{filename}
quarantine/{partner_id}/{transfer_id}/{filename}
processed/{partner_id}/{yyyy}/{mm}/{dd}/{transfer_id}/{filename}
egress/{partner_id}/{transfer_id}/... # staging for outbound SFTP
multipart/{partner_id}/{upload_id}/part-{n} # optional for API uploads
PrefixWriterReaderLifecycle
landing/Transfer Family / APIValidatorsExpire incomplete after 7d
quarantine/ValidatorsSecurity opsRetain 90d+ for forensics
processed/RoutersDownstream / auditTier to IA after 30d
egress/Egress workersTransfer Family outboundDelete after ACK

10.2 DynamoDB data model​

Table: mft-transfers

AttributeTypeKeyDescription
pkStringPKPARTNER#{partner_id}
skStringSKTRANSFER#{transfer_id}
idempotency_keyStringGSI1 PKpartner_id#remote_name#checksum
statusString—See state machine
s3_bucket / s3_keyString—Landing object
checksum_sha256String—Content hash
bytesNumber—Object size
protocolString—sftp | https | as2
attemptNumber—Delivery attempts
lease_owner / lease_untilString / Number—Worker claim
error_codeString—Last failure class
created_at / updated_atString—ISO-8601
ttlNumber—Optional expire for COMPLETED

GSI1: idempotency_key → return prior SUCCESS (duplicate upload).
GSI2: status + updated_at → ops “stuck transfers” dashboard.

Table: mft-partners

AttributeTypeDescription
partner_idPKStable ID
display_nameStringOps UI
sftp_usernameStringTransfer Family mapping
landing_prefixStringIAM-scoped path
kms_key_arnStringTenant CMK
allowed_source_cidrsListNetwork allow list
max_file_bytesNumberQuota
routing_rulesMapTarget bucket / SNS / SFTP egress
sla_window_cronStringBatch window
scan_requiredBoolMalware gate
enabledBoolKill switch

Table: mft-audit (or S3 + Athena)

Append-only events: RECEIVED, VALIDATED, QUARANTINED, ROUTED, SUCCEEDED, FAILED, REPLAYED with actor, request_id, hashes.

Step-by-step flow:

StepRelationExplanation
1Partner → TransferOne partner, many transfers
2Transfer → AuditAppend-only lifecycle events
3Partner → KMSTenant encryption key
4Transfer → S3Blob pointer (bucket + key)

10.3 API contracts​

POST /v1/transfers — initiate HTTPS upload

{
"partner_id": "acme-edi",
"filename": "ORDERS_20260829.edi",
"bytes": 1048576,
"checksum_sha256": "ab12...",
"idempotency_key": "acme-edi:ORDERS_20260829.edi:ab12...",
"content_type": "application/edi-x12"
}

Response 201:

{
"transfer_id": "tr_01J8...",
"status": "PENDING_UPLOAD",
"upload": {
"mode": "multipart",
"bucket": "mft-prod-us-west-2",
"key": "landing/acme-edi/2026/08/29/tr_01J8.../ORDERS_20260829.edi",
"part_size_bytes": 16777216,
"presigned_parts": ["https://...", "..."]
}
}

POST /v1/transfers/{transfer_id}/complete

{ "parts": [{"etag": "...", "part_number": 1}], "checksum_sha256": "ab12..." }

GET /v1/transfers/{transfer_id}

{
"transfer_id": "tr_01J8...",
"status": "SUCCEEDED",
"processed_key": "processed/acme-edi/.../ORDERS_20260829.edi",
"attempts": 1
}
HTTPMeaning
200Idempotent replay of initiate/complete
201New transfer created
409Conflict — different body for same idempotency key
413Exceeds max_file_bytes
422Checksum mismatch on complete
503Control plane overload — retry same key

SFTP path (no REST): Transfer Family writes to landing/...; EventBridge creates the transfer row if missing (server-assigned transfer_id + hash-after-land).

10.4 Transfer Family LLD​

SettingProduction choiceWhy
Endpoint typeVPC + Elastic IP / NLBPrivate or controlled public
IdentityCustom IdP Lambda → Secrets ManagerPer-partner users/keys
Home directoryLogical → S3 prefix mappingEnforce landing/{partner_id}/
Session policyGenerated IAMDeny cross-partner keys
ProtocolsSFTP (SSH)FTPS/AS2 as add-ons
LoggingCloudWatch + CloudTrailSession forensics
Passive mode / portsDocumented for partner firewallsGame-day connectivity tests

10.5 EventBridge → SQS → Step Functions​

EventBridge rule (simplified):

{
"source": ["aws.s3"],
"detail-type": ["Object Created"],
"detail": {
"bucket": {"name": ["mft-prod-us-west-2"]},
"object": {"key": [{"prefix": "landing/"}]}
}
}

Target: SQS mft-validate (not Lambda directly — backpressure).

Step Functions — validate & route (conceptual ASL):

{
"Comment": "MFT validate-route",
"StartAt": "ClaimTransfer",
"States": {
"ClaimTransfer": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "mft-claim", "Payload.$": "$" },
"Next": "Validate"
},
"Validate": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "mft-validate", "Payload.$": "$" },
"Retry": [{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 30,
"MaxAttempts": 3,
"BackoffRate": 2.0
}],
"Catch": [{
"ErrorEquals": ["MalwareDetected", "SchemaInvalid"],
"ResultPath": "$.error",
"Next": "Quarantine"
}],
"Next": "SizeGate"
},
"SizeGate": {
"Type": "Choice",
"Choices": [{
"Variable": "$.bytes",
"NumericGreaterThan": 104857600,
"Next": "LargeFileRoute"
}],
"Default": "SmallFileRoute"
},
"SmallFileRoute": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "mft-route-small", "Payload.$": "$" },
"Next": "MarkSucceeded"
},
"LargeFileRoute": {
"Type": "Task",
"Resource": "arn:aws:states:::ecs:runTask.sync",
"Next": "MarkSucceeded"
},
"Quarantine": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "mft-quarantine", "Payload.$": "$" },
"Next": "MarkFailed"
},
"MarkSucceeded": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"End": true
},
"MarkFailed": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"End": true
}
}
}

10.6 Worker pseudocode (claim + idempotency)​

def handle_object_created(event: dict) -> None:
partner_id, key, etag, bytes_ = parse_s3_event(event)
checksum = head_or_compute_sha256(bucket, key, bytes_)
idem = f"{partner_id}#{basename(key)}#{checksum}"

try:
ddb.put_item(
Table="mft-transfers",
Item=new_transfer(partner_id, key, checksum, idem),
ConditionExpression="attribute_not_exists(idempotency_key)",
)
except ConditionalCheckFailedException:
existing = get_by_idempotency(idem)
if existing["status"] == "SUCCEEDED":
return # safe no-op
# else continue / resume FAILED with new attempt

start_execution(state_machine_arn, name=execution_name(idem), input=...)


def mark_succeeded(transfer_id: str, processed_key: str) -> None:
ddb.update_item(
Key=transfer_keys(transfer_id),
UpdateExpression="SET #s=:s, processed_key=:p, updated_at=:t",
ConditionExpression="#s <> :done", # prevent double notify
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={
":s": "SUCCEEDED",
":done": "SUCCEEDED",
":p": processed_key,
":t": now(),
},
)
emit_event("transfer.succeeded", transfer_id)

10.7 IAM sketch (least privilege)​

Transfer Family session (partner A):

{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::mft-prod-us-west-2",
"arn:aws:s3:::mft-prod-us-west-2/landing/acme-edi/*"
],
"Condition": {
"StringLike": { "s3:prefix": ["landing/acme-edi/*"] }
}
}

Validate Lambda role: s3:GetObject on landing/*, s3:PutObject on quarantine/*, kms:Decrypt on partner CMK, dynamodb:PutItem/UpdateItem on transfers, states:StartExecution denied (SF invokes Lambda — not reverse).

Route Lambda role: s3:CopyObject landing→processed, sns:Publish, no DeleteObject on quarantine.

10.8 Large-file path (detail)​

Rules students must say in interview:

  1. Never Body.read() a multi-GB object into Lambda memory.
  2. Multipart upload + server-side copy.
  3. Streaming checksum; same idempotency key as small path.
  4. ECS/Batch/Fargate for CPU-heavy parse; Lambda only for orchestration glue.

10.9 Observability metrics & alarms​

MetricSourceAlarm
transfers_receivedCustom EMF—
transfers_succeeded / failedCustomError rate > 2% for 10m
validate_latency_ms p95SF / Lambda> 120s
sqs_visible_messages validateSQS> 10k for 15m
sqs_dlq_messagesDLQ> 0 for 5m → page
oldest_pending_age_secondsCustom from DDB> SLA window
transfer_family_auth_failuresCW logs metricSpike → cert/key issue
s3_replication_latencyS3 CRR> RPO
partner_disabled_uploadsCustomUnexpected drop

Trace: transfer_id in SF execution name, Lambda logs, S3 object tags (transfer_id, partner_id).

10.10 Terraform module map (interview whiteboard)​

Partner onboarding PR = Terraform workspace input: username, CIDRs, KMS, routing_rules → no manual IAM in console.

Stakeholder gap analysis (PM / EM / AVP): EFT IaC Pipeline — Current → Target — 26 maturity pillars, gap register, investment asks.


10A. Five production pillars (interview + game day)​

These five topics are what principal interviews and game days actually probe. Master the diagrams and the one-liners.


10A.1 Idempotency — complete LLD​

Guarantee: At-least-once processing, at-most-once business effect (route / notify / charge partner once).

Key design​

FieldProduction choiceWhy
Idempotency keypartner_id # remote_name # sha256Content-addressed; rename≠new content if hash same
Client key (HTTPS)Partner-supplied UUID in Idempotency-Key headerSafer for “same file, new name” contracts
ScopePer partner (never global)Tenant isolation
TTL7–90 days on GSI / itemBound storage; align with partner SLA
Request hashHash of routing intent + bytesDetect key reuse with different body → 409
Execution nameSF name = hash(idempotency_key)Prevents duplicate state machines

Step-by-step flow:

StepActionInterview words
1Build key“SFTP is not exactly-once; we invent the key.”
2Conditional writeDynamoDB = compare-and-set
3a–dBranch on prior stateSuccess no-op; in-flight join; failed = policy
5CAS to SUCCEEDEDSecond notifier loses — exactly-once notify

Idempotency state machine​

DynamoDB condition expressions (copy onto board)​

# Claim new
PutItem Condition: attribute_not_exists(idempotency_key)

# Finish once
UpdateItem SET status=SUCCEEDED
Condition: status IN (IN_PROGRESS, ROUTING) # or status <> SUCCEEDED

# Conflict body
If key exists AND request_hash != new_hash → HTTP 409

Game day — idempotency (GD-I)​

InjectExpect
Two workers same object eventOne SUCCEEDED; one no-op; one SNS transfer.succeeded
Same key, different checksum409 or new key if name differs by policy
Crash after route before CASReplay may re-copy; target must be idempotent or use copy-if-not-exists

Principal signal: “Idempotency of our platform ≠ idempotency of downstream. We still design target writes to be safe under at-least-once.”


10A.2 Duplicate file transfer handling​

Duplicates are normal in MFT: partner retries, dual NICs, ops re-drop, EventBridge redrive.

Duplicate taxonomy​

TypeExamplePlatform behavior
Exact duplicateSame name + same SHAIdempotency hit → no second route
Retry duplicateSame name, new upload, same SHASame as exact
Content changeSame name, different SHANew transfer (or 409 if client key reused)
Name collisionDifferent name, same SHAPolicy: allow (two logical files) or dedupe by hash-only
Partial then fullTruncated then completeQuarantine partial; full is new attempt
Cross-region echoCRR + reprocessactive_region + processed marker prevents double

Decision table (ops + interview)​

Same partner?Same remote_name?Same SHA?Action
YYYDedup — return prior transfer_id
YYNNew version — supersede or parallel per policy
YNYHash-dedup policy optional
YNNNew transfer
N**Always separate tenants

Landing object strategy​

Production tip: Prefer immutable landing keys (…/{transfer_id}/{filename}) so S3 versions don’t confuse audits; idempotency lives in DynamoDB, not object overwrite semantics.

Game day — duplicates (GD-3 expanded)​

  1. Upload ORDERS.edi (SHA=X) → expect SUCCEEDED + one target object.
  2. Re-upload identical bytes → expect same transfer_id, no second target object, metric idempotent_hit=1.
  3. Upload same name SHA=Y → expect new transfer; target has version or new key per routing rule.
  4. Verify CloudWatch: transfers_succeeded +1 then +0; duplicate_suppressed +1.

10A.3 Replay — complete LLD​

Replay = intentionally re-drive work for a known transfer_id after failure or ops fix — without creating a silent second business effect.

Replay vs retry vs duplicate​

MechanismWho starts itIdempotency
Auto retryStep Functions / SQSSame execution; backoff
Duplicate uploadPartnerSame idempotency key → no-op if SUCCEEDED
Ops replayHuman / ticketExplicit replay_id; CAS guards

Step-by-step flow:

StepGuardWhy
1–2AuthZ — ops role onlyPartners cannot self-replay billing events
3aBlock SUCCEEDED by defaultPrevent accidental double delivery
3b–4Bump attempt; unique SF nameObservability + no colliding executions
5Target idempotent writeDefense in depth
6–7CAS + auditCompliance trail for game day

Replay API contract​

POST /v1/transfers/tr_01J8.../replay
Authorization: Bearer <ops>
Content-Type: application/json

{
"reason": "GD-7 target restored",
"mode": "from_failed", // from_failed | from_dlq | force_reprocess
"force": false
}
CodeMeaning
202Replay started
409Already SUCCEEDED and force=false
404Unknown transfer
403Caller not in mft-ops role

DLQ replay pipeline​

Rules: Never raw-redrive malware quarantines into route; never replay without transfer_id correlation; always write REPLAYED audit with operator identity.

Game day — replay (GD-7 / GD-R)​

StepPass criteria
Inject target 5xx until DLQMessages in DLQ; transfers FAILED
Fix target; replay 100 idsAll SUCCEEDED; target row count +100 not +200
Attempt replay of SUCCEEDED409
Audit export100 REPLAYED events with same operator

10A.4 DR switch — complete LLD​

DR switch = controlled cutover of write path (ingress + control plane) to the standby region with measured RPO/RTO and no split-brain.

Control flags (SSM / AppConfig)​

ParameterValuesPurpose
/mft/active_regionus-west-2 | us-east-1Writers follow this
/mft/failover_modenormal | dr_active | failback_freezeSplit-brain lock
/mft/ingress_endpointDNS namePartner CNAME target

Switch sequence (numbered — memorize)​

Step-by-step flow:

StepActionFailure if skipped
1Dual-signal detectFlapping false failover
2–3Flags before DNSSplit-brain writes
4–6DNS + warm ingress + workersPartners connect nowhere
7Measure lagUnknown data loss
8–9Write DR; resume stateOrphan in-flight
10–12Comms + canary + clockFailed game day score

In-flight transfer handling on switch​

State at cutAction on DR
SUCCEEDEDNo-op
FAILEDEligible for replay after stabilize
IN_PROGRESSWorkers reclaim lease if lease_until expired
Object in landing, no DDB rowSweeper lists prefix → create transfer
SQS message only on primaryAssume lost — sweeper is source of truth (S3 + DDB)

Failback (often harder than failover)​

Game day — DR switch (GD-8 expanded)​

ClockCheckpoint
T+0Inject primary impairment (deny TF / block AZ)
T+5Alarms fire; IC declared
T+15Flags set; DNS flipped
T+30Canary SUCCEEDED on DR
T+45Report RPO from ReplicationLatency + sample object
T+60Scorecard + in-flight reconcile count

Pass: RTO ≤ documented SLO; zero duplicate SUCCEEDED for same idempotency key across regions; partner canary green.


10A.5 Back-of-envelope — tie to architecture​

Use §4 numbers when defending component choices:

NumberArchitecture consequence
12/s avgDon’t overbuild; managed services win
100/s peakSQS + concurrency caps mandatory
~26 TB/dayLifecycle + large-file path; cost dashboards
200 Lambda concurrentReserved concurrency + size gate
5–8 DDB writes/transferOn-demand; PK = PARTNER#id avoids hot partition if one partner is 50% traffic → consider random suffix or daily shard
RPO 15 minS3 RTC on critical prefixes
RTO 60 minWarm TF + documented GD-8

11. HA, DR, and Multi-Region (LLD)​

ConcernStrategy
AZ failureS3/DDB/Lambda multi-AZ — no human action
Regional failureFailover DNS + warm Transfer Family + CRR buckets
Split-brainSingle active_region in SSM; partners updated via runbook
In-flight transfersResume from DDB state; re-drive SQS; accept at-least-once
FailbackReverse replication + freeze writes on DR first
RPO/RTOMeasure CRR + DDB lag in game day — not aspirational slides

Deep dive: Full DR switch sequence, flags, in-flight handling, and failback → §10A.4. Idempotency / duplicates / replay → §10A.1–10A.3. Capacity math → §4.


12. Game Day Playbooks​

Use these in mock interviews (“what happens when…”) and real ops drills. Each drill has inject → detect → mitigate → verify → learn.

12.1 Game day catalog​

#DrillFrequencyPrimary SLO under test
GD-1Partner batch flood (20× avg)QuarterlyBackpressure / complete-in-window
GD-2Poison malware fileQuarterlyFail closed; no fan-out
GD-3Duplicate file same dayMonthly (automated)Idempotent SUCCEEDED
GD-4Partial multipart / truncated SFTPQuarterlyQuarantine incomplete
GD-5Validate Lambda OOM on large fileSemi-annualSize gate → ECS path
GD-6Partner SSH key expirySemi-annualAuth failure alert + rotation
GD-7Downstream target 5xx stormQuarterlyRetry + DLQ; no lost state
GD-8Primary region impairmentAnnualRTO/RPO measured
GD-9DynamoDB throttlingSemi-annualOn-demand / partition keys
GD-10Accidental cross-tenant IAMAnnual (security)Deny + detection

12.2 GD-1 — Batch flood (backpressure)​

Operator checklist:

  1. Confirm landing writes succeed (S3 is the buffer).
  2. Do not remove SQS — that removes backpressure.
  3. Scale workers to documented max, not infinity.
  4. Communicate SLA risk if window will miss.
  5. Postmortem: was peak in capacity model?

12.3 GD-2 — Malware / poison file​

Pass criteria: zero objects in processed/ for that transfer_id; partner notified; audit row QUARANTINED.

12.4 GD-3 — Duplicate delivery​

Inject: Upload identical file twice (same name + checksum).
Pass criteria: one transfer.succeeded business effect; second API/SFTP results in SUCCEEDED no-op; target system receives once (verify with idempotent consumer counter).

12.5 GD-7 — Downstream outage​

Runbook — replay from DLQ:

  1. Inspect payload + transfer_id.
  2. Confirm target healthy.
  3. StartExecution with replay=true or redrive SQS.
  4. Conditional update still prevents double SUCCESS notify.
  5. Close incident with count of replayed messages.

12.6 GD-8 — Region failover (full drill)​

PhaseActionsClock
DetectHealth: Transfer Family, API 5xx, AWS Health0–10m
DecideIC declares failover; freeze nonessential changes10–15m
Executeactive_region=dr; DNS/partner endpoint cutover; scale DR workers15–45m
ValidateCanary upload; status API; CRR lag = RPO sample45–60m
CommunicateStatus page; partner bulletinParallel
LearnRecord actual RTO/RPO; gap listAfter

12.7 Game day scorecard (print for students)​

CheckPass?
Detected via documented alarm (not Slack luck)☐
Mitigated without breaking idempotency☐
Customer/partner comms template used☐
Metrics prove recovery (graph attached)☐
Runbook step numbers matched reality☐
Follow-up tickets filed same day☐

13. Interview LLD drill (45–60 min)​

Practice aloud using this board order:

MinuteWhat to draw / say
0–5Clarify protocols, size, SLA, DR, security
5–15Five boxes: ingress → S3 → queue → workers → DDB
15–25Idempotency key + CAS; duplicate decision table
25–30Numbered happy-path sequence
30–40Replay API vs retry vs duplicate; DLQ
40–50BOE: 12/s → 100/s peak; DDB WRU; Lambda concurrency
50–60DR switch steps 1–12 + one game day

Strong close: “12/s average is easy; we design for ~100/s peaks, idempotent effects under duplicates, ops replay without double delivery, and a measured DR switch.”


14. Architecture diagram index​

#DiagramSectionInterview / Game day
1Interview flow§1Open strong
2Clarify mindmap§2Requirements
3Scope in/out§3 SBound problem
4AWS topology§3 TPrimary HLD
5Happy-path sequence§3 TTimed talk
6Lifecycle states§3 TCorrectness
7–10Backpressure / size / idempotency / tenants§3 ETrade-offs
11Failure / DLQ§3 PProduction
12C4 context§9.1HLD
13Component interaction§9.3Production path
—SLO math + achievement§9.4Interview confidence
14S3 prefix flow§10.1LLD storage
15Entity relationships§10.2Data model
16Transfer Family auth§10.4Ingress LLD
17SF state machine§10.5Orchestration
18Large-file sequence§10.8Anti-Lambda-GB
19Terraform modules§10.10Platform ops
26Pillars overview§10AInterview map
27–28Idempotency flow + states§10A.1Exactly-once effect
29–30Duplicate taxonomy§10A.2Partner retries
31–32Replay sequence + DLQ§10A.3Ops game day
33–35DR switch + in-flight + failback§10A.4GD-8
36BOE → architecture§10A.5Tie numbers to design
20Multi-region§11DR summary
21–24Game day flows§12Ops drills
25Interview timer§13Mock interview
—Throughput / bytes / WRU§4Back-of-envelope

ResourceUse
Global File Transfer PlatformFull reference architecture
Enterprise File Transfer StoriesSTAR behavioral templates
IdempotencyDuplicate delivery
AWS S3 Multi-Region DRCross-region durability
Transactional OutboxReliable downstream notify
Multi-Region ArchitectureFailover patterns

16. Hands-On Lab (local)​

Runnable control plane for this scenario. No AWS account. One command is enough to record.

cd labs/lab-018-enterprise-file-transfer
python3 -m src.main --demo

The demo lands a partner file, suppresses a duplicate, rejects a bad checksum, quarantines a malware marker, and replays a failed route exactly once.

LabLab 018 README
APIpython3 -m src.main --serve on :8107
Curl scriptscripts/demo_transfer.sh
Cost$0 locally. The AWS path in labs/lab-018-enterprise-file-transfer/aws is pay-per-use (S3, SQS, Lambda, DynamoDB) and about $0 while idle.

AWS demo (real services, minimal cost)​

This is the recording path. It runs in us-west-2 on account 277374794397. ./demo-aws.sh already completed once against the live stack: one route, one duplicate, one quarantine, and one failed route that replayed into a single success.

cd labs/lab-018-enterprise-file-transfer/aws
terraform init && terraform apply
./demo-aws.sh
terraform destroy

Destroy the stack after the video. Idle cost of this stack is about $0 per hour. A full run is under $0.01.

What the stack is​

ResourceNameRole in the demo
S3paks-mft-demo-277374794397landing/, processed/, quarantine/. SSE-S3. Public access blocked. Objects expire after 7 days. EventBridge notifications are on.
EventBridge rulepaks-mft-demo-277374794397-landingObject Created on this bucket, object key prefix landing/
SQS…-validateOne message per landing object. Visibility timeout 60s. After 3 failed receives the message goes to …-dlq (kept 1 day).
Lambdapaks-mft-demo-277374794397Python 3.12, 256 MB, 30s timeout, batch size 1. Claims, scans, copies.
DynamoDBpaks-mft-demo-277374794397On-demand. Hash key pk.
CloudWatch Logs/aws/lambda/paks-mft-demo-277374794397Retained 3 days

The partner drop in this recording is aws s3 cp. Transfer Family stays off the stack: an idle SFTP endpoint bills about $0.30 per hour. There is no NAT gateway and no KMS customer managed key. One Lambda does the work the production design splits across Step Functions states.

What happens on every file​

The script and the Lambda share one idempotency key:

pk = partner # filename # sha256(bytes)
partner = acme-edi
  1. The script writes a temp file and copies it to s3://paks-mft-demo-277374794397/landing/acme-edi/<filename>.
  2. S3 emits Object Created because the bucket has EventBridge enabled.
  3. The rule keeps events whose key starts with landing/ and sends them to the validate queue. Copies into processed/ and quarantine/ do not re-enter the pipeline.
  4. Lambda reads the SQS body. A normal event is the EventBridge envelope. A replay is a small JSON message the script sends itself: {"replay":true,"bucket":"...","key":"landing/acme-edi/INVOICE.csv"}.
  5. Lambda downloads the object, lowercases user metadata, and hashes the bytes.
  6. It tries PutItem with attribute_not_exists(pk). The first writer creates transfer_id = tr_ plus 12 hex characters, status RECEIVED, route_count = 0, attempt = 1. A second writer gets ConditionalCheckFailedException and reads the existing row.
  7. Decision on that row:
Existing statusNormal deliveryReplay message
noneValidate, then copy or failSame, and attempt increases on success
SUCCEEDEDduplicate_count + 1. No copy.Route again only if you send replay (the script never does this for a success)
QUARANTINEDduplicate_count + 1. No copy.Would re-scan
FAILEDLeave it. Ops must replay.Skip the outage flag and route once
  1. Malware is fail-closed before routing. A match is the filename ending in .malware, or EICAR / X5O! in the first 4096 bytes. The object is copied to quarantine/{partner}/{transfer_id}/{filename} and the row becomes QUARANTINED / MALWARE.
  2. User metadata fail-route=true on the first attempt simulates a downstream route outage. Lambda writes FAILED / ROUTE_UNAVAILABLE and does not copy. On replay that flag is ignored.
  3. Otherwise Lambda copies to processed/{partner}/{transfer_id}/{filename}, sets SUCCEEDED, clears error_code, and increments route_count by 1.
  4. The script polls GetItem every 2 seconds, up to 60 seconds, and prints the row.

Step 1 — first EDI file routes once​

The script writes ISA*00*ORDER*ACME*20261015~ (27 bytes) and uploads it to landing/acme-edi/ORDERS.edi.

FieldValue from the live run
pkacme-edi#ORDERS.edi#1a86cedf83d725be45137f328cb44d202e0754e137e8e3ca481554e8410c8de4
transfer_idtr_37fa56d72aee
statusSUCCEEDED
route_count1
duplicate_count0
Copyprocessed/acme-edi/tr_37fa56d72aee/ORDERS.edi

Say: "The partner drops an EDI file. S3 tells EventBridge, the queue wakes Lambda, DynamoDB claims the hash, and we route that object once."

Step 2 — the same bytes are a duplicate​

The script uploads the identical temp file to the same key. SHA-256 matches, so pk matches. The conditional put loses. Lambda sees SUCCEEDED, adds 1 to duplicate_count, and returns.

FieldAfter step 2
transfer_idstill tr_37fa56d72aee
route_countstill 1
duplicate_count1
New processed objectnone

Say: "S3 delivery is at-least-once. The business effect is once. Same partner, same name, same hash — we return the original success."

Step 3 — malware is quarantined​

The script writes EICAR-TEST-FILE (15 bytes) to landing/acme-edi/payload.bin. Lambda finds EICAR in the body, copies the object to quarantine, and does not route it.

FieldValue from the live run
pkacme-edi#payload.bin#9ff11dad6845de3c38d1f4e76a763cb97105acfdb70949b488cd90c14c36a16a
transfer_idtr_bfd8ab9e1088
statusQUARANTINED
error_codeMALWARE
route_count0
Copyquarantine/acme-edi/tr_bfd8ab9e1088/payload.bin

Say: "The scanner fails closed. Quarantine keeps the evidence. Nothing downstream sees this object."

Step 4 — route outage, then one replay​

The script uploads INV,1001,250.00 plus a newline (16 bytes) with --metadata fail-route=true. S3 stores that as user metadata. On the first Lambda invocation fail-route is true and replay is false, so the row stops at FAILED.

FieldBefore replay
pkacme-edi#INVOICE.csv#2da36e24a5e98ce967bacf027005a5a79088b19e577e1ab8841a7cc8125beb34
transfer_idtr_869134ee4044
statusFAILED
error_codeROUTE_UNAVAILABLE
route_count0

The script then sends one SQS message onto the same validate queue:

{"replay":true,"bucket":"paks-mft-demo-277374794397","key":"landing/acme-edi/INVOICE.csv"}

Lambda takes the replay branch, ignores fail-route, copies the landing object, and updates the same row.

FieldAfter replay
transfer_idstill tr_869134ee4044
statusSUCCEEDED
error_codeempty
route_count1
attempt2
Copyprocessed/acme-edi/tr_869134ee4044/INVOICE.csv

A second ordinary S3 event for this object would see SUCCEEDED and only bump duplicate_count. The script stops after the first successful replay.

Say: "The file stayed in landing while the router was down. Replay uses the same idempotency key, so we deliver once."

What the console shows at the end​

processed/acme-edi/tr_37fa56d72aee/ORDERS.edi 27 bytes
processed/acme-edi/tr_869134ee4044/INVOICE.csv 16 bytes
quarantine/acme-edi/tr_bfd8ab9e1088/payload.bin 15 bytes

Landing objects remain until the 7-day lifecycle rule deletes them. Re-running ./demo-aws.sh reuses the same hashes, so steps 1–3 print the existing rows and increment duplicate counts. Delete the three DynamoDB items first if you want a clean first-time claim on camera.

cd labs/lab-018-enterprise-file-transfer/aws
terraform destroy

17. Source​

Interview question framing and AWS building blocks summarized from:

Designing a Secure Enterprise File-Transfer Platform with AWS — LinkedIn