AWS Builder Center
Event-Driven SFTP Architecture on AWS: Transfer Family, S3, EventBridge, and Lambda for Partner Files

Event-Driven SFTP Architecture on AWS: Transfer Family, S3, EventBridge, and Lambda for Partner Files

How to build a serverless SFTP ingestion pipeline for partner settlement files with AWS Transfer Family, S3, EventBridge, and Lambda: per-partner isolation, automatic validation, quarantine, audit trail, and alerts, with no servers to patch.

Senior Data & AI Engineer
If you work with banks, payment processors, insurers, or healthcare partners, you already know the truth: in 2026, a lot of critical data still arrives as a file dropped onto an SFTP server. The protocol isn't going anywhere, but the way we handle those files can look very different from the classic setup, which is an EC2 instance running OpenSSH, a cron job that polls a directory every five minutes, and a shell script nobody wants to touch.
This post walks through a serverless alternative: AWS Transfer Family for the SFTP endpoint, Amazon S3 for storage, Amazon EventBridge to react to uploads, and AWS Lambda to validate and route each file. The example is a fintech one, partners dropping daily settlement CSVs, but the pattern applies to any inbound file feed.




The scenario and the requirements

Imagine several payment partners who each send one settlement file per day ( settlement_YYYY-MM-DD.csv ). The platform team needs to:
  1. Isolate partners. Each partner can only see and write to their own folder, and never learns the bucket name.
  1. Validate before anything downstream sees the file. A malformed or empty file should never reach the warehouse.
  1. React immediately, without polling. No cron job, no "check every five minutes".
  1. Keep an audit trail. Who sent what, when, how big, and what happened to it.
  1. Alert people. Ops gets told about failures; partners get told when their file is rejected.
  1. Run without servers to patch.

Why events, and which events?

There are three common ways to trigger processing when a file arrives. I picked the third, but the first two are legitimate depending on your needs.
Approach
Good at
Watch out for
S3 Event Notifications
Works for any upload path, not just SFTP
No SFTP username or protocol context; can loop if your processing writes back into a watched prefix; no SFTP-specific failure events
Transfer Family managed workflows
Built-in steps (copy, tag, delete, decrypt) plus a custom Lambda step, configured on the server
Per-GB processing charge; less flexible for fan-out and routing across several consumers
Transfer Family events via EventBridge
Event carries  username ,  file-path ,  bytes ,  etag , and  server-id ; filterable by user or path; separate failure events; easy fan-out to Lambda, Step Functions, SNS, SQS
You own the processing logic; EventBridge delivery is at-least-once, so handlers must be idempotent
Transfer Family publishes server events straight to EventBridge with  source  set to  aws.transfer , and the  detail-type  tells you what happened, for example  SFTP Server File Upload Completed  or  SFTP Server File Upload Failed . Because the event is emitted by the SFTP layer, it only fires for files that arrive over SFTP. Your Lambda moving a file to  validated/  produces no new Transfer Family event, so there's no feedback loop to design around.

Step 1: Create the bucket

One bucket, three top-level prefixes:
settlement-landing-bucket/
├── inbound/<partner>/ <- partners write here (SFTP home)
├── validated/<partner>/<date>/ <- passed validation
└── quarantine/<partner>/<date>/ <- failed validation, kept for review
Baseline settings I'd turn on from day one:
  • Block Public Access (all four settings).
  • Default encryption with SSE-KMS using a customer managed key, so you control who can decrypt.
  • A bucket policy that denies non-TLS requests ( aws:SecureTransport = false ).
  • Versioning, plus an optional lifecycle rule to expire  quarantine/  objects after your review window.

Step 2: Create the SFTP server

For a quick start a public endpoint is fine. For production I'd use a VPC-hosted endpoint with a security group that allow-lists partner IP ranges (and Elastic IPs if partners need to allow-list you).
aws transfer create-server \
--domain S3 \
--protocols SFTP \
--identity-provider-type SERVICE_MANAGED \
--endpoint-type PUBLIC \
--structured-log-destinations arn:aws:logs:<region>:<account-id>:log-group:/aws/transfer/settlement-sftp
Pick the most recent recommended security policy for your server so older ciphers and key-exchange algorithms stay disabled, and keep structured logging on, because those logs are what you'll reach for at 2 a.m.

Step 3: Create one user per partner

Each partner gets their own user, their own SSH key, their own IAM role, and a logical home directory. Logical directories map a clean virtual path ( / ) onto the real S3 prefix, so the partner never sees the bucket name or anyone else's data.
aws transfer create-user \
--server-id s-xxxxxxxxxxxxxxxxx \
--user-name acme-payments \
--role arn:aws:iam::<account-id>:role/transfer-partner-acme \
--home-directory-type LOGICAL \
--home-directory-mappings '[{"Entry":"/","Target":"/settlement-landing-bucket/inbound/acme"}]' \
--ssh-public-key-body "ssh-ed25519 AAAA... acme-payments"
The IAM role is where least privilege lives. This one is upload-only and scoped to a single prefix:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListOwnPrefixOnly",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::settlement-landing-bucket",
"Condition": { "StringLike": { "s3:prefix": ["inbound/acme", "inbound/acme/*"] } }
},
{
"Sid": "UploadToOwnPrefix",
"Effect": "Allow",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::settlement-landing-bucket/inbound/acme/*"
},
{
"Sid": "UseBucketKey",
"Effect": "Allow",
"Action": ["kms:GenerateDataKey", "kms:Decrypt"],
"Resource": "arn:aws:kms:<region>:<account-id>:key/<key-id>"
}
]
}
If a partner's client also needs to read back or resume uploads, add  s3:GetObject  for that same prefix and test with their actual client. SFTP clients differ in what they ask for.

Step 4: Route upload events with EventBridge

This rule matches successful SFTP uploads of CSV files:
{
"source": ["aws.transfer"],
"detail-type": ["SFTP Server File Upload Completed"],
"detail": {
"status-code": ["COMPLETED"],
"file-path": [{ "suffix": ".csv" }]
}
}
A real-world wrinkle: many partners upload to a temporary name ( file.csv.tmp ) and then rename the file when the upload finishes, so downstream systems never see half-written files. In that case the finished file arrives as a rename event, not an upload event. Transfer Family emits  SFTP Server File Rename Completed  with a  renamed-file-path  field, so a rule that handles both looks like this:
{
"source": ["aws.transfer"],
"$or": [
{
"detail-type": ["SFTP Server File Upload Completed"],
"detail": { "file-path": [{ "suffix": ".csv" }] }
},
{
"detail-type": ["SFTP Server File Rename Completed"],
"detail": { "renamed-file-path": [{ "suffix": ".csv" }] }
}
]
}
Ask each partner how their client behaves, then test both paths before go-live. A second rule on  SFTP Server File Upload Failed  (the  failure-code  field distinguishes causes such as  PARTIAL_UPLOAD ) can send straight to SNS so ops hears about broken transfers.
Wire the rule to the Lambda function:
aws events put-rule --name settlement-file-arrived --event-pattern file://pattern.json

aws events put-targets --rule settlement-file-arrived \
--targets "Id=validator,Arn=arn:aws:lambda:<region>:<account-id>:function:settlement-validator"

aws lambda add-permission --function-name settlement-validator \
--statement-id eventbridge-invoke --action lambda:InvokeFunction \
--principal events.amazonaws.com \
--source-arn arn:aws:events:<region>:<account-id>:rule/settlement-file-arrived
An upload event looks like this (trimmed; field names per the Transfer Family events reference):
{
"detail-type": "SFTP Server File Upload Completed",
"source": "aws.transfer",
"detail": {
"status-code": "COMPLETED",
"protocol": "SFTP",
"bytes": 1048576,
"etag": "b6d81b360a5672d80c27430f39153e2c",
"file-path": "/settlement-landing-bucket/inbound/acme/settlement_2026-11-01.csv",
"server-id": "s-xxxxxxxxxxxxxxxxx",
"username": "acme-payments",
"session-id": "..."
}
}
Note that  file-path  starts with the bucket name, so the Lambda splits it into bucket and key.

Step 5: The validator Lambda

The function does cheap checks first, reads only the first 64 KB to check the CSV header (so a 500 MB file doesn't mean 500 MB of memory), moves the file, writes an audit row, and notifies.




import csv
import json
import logging
import os
from datetime import datetime, timezone

import boto3
from botocore.exceptions import ClientError

log = logging.getLogger()
log.setLevel(logging.INFO)

s3 = boto3.client("s3")
sns = boto3.client("sns")
audit = boto3.resource("dynamodb").Table(os.environ["AUDIT_TABLE"])
TOPIC_ARN = os.environ["TOPIC_ARN"]

REQUIRED_COLUMNS = {"settlement_id", "merchant_id", "amount", "currency", "settled_at"}
MAX_BYTES = 500 * 1024 * 1024 # 500 MB

def _path(detail):
# Upload events carry file-path; rename events carry renamed-file-path
return detail.get("file-path") or detail["renamed-file-path"]

def _validate(bucket, key, size):
"""Return a rejection reason, or None if the file looks fine."""
if size == 0:
return "empty file"
if size > MAX_BYTES:
return f"file too large ({size} bytes)"
if not key.lower().endswith(".csv"):
return "unexpected file extension"

head = s3.get_object(Bucket=bucket, Key=key, Range="bytes=0-65535")["Body"].read()
text = head.decode("utf-8-sig", errors="replace")
first_line = (text.splitlines() or [""])[0]
columns = {c.strip().lower() for c in next(csv.reader([first_line]), [])}
missing = REQUIRED_COLUMNS - columns
if missing:
return f"missing columns: {sorted(missing)}"
return None

def handler(event, context):
detail = event["detail"]
partner = detail["username"]
bucket, _, key = _path(detail).lstrip("/").partition("/")
filename = key.rsplit("/", 1)[-1]

try:
head = s3.head_object(Bucket=bucket, Key=key)
except ClientError as e:
if e.response["Error"]["Code"] in ("404", "NoSuchKey", "NotFound"):
# Already moved by an earlier (retried or duplicate) invocation
log.warning("Object gone, skipping: s3://%s/%s", bucket, key)
return {"status": "gone"}
raise

reason = _validate(bucket, key, head["ContentLength"])
status = "QUARANTINED" if reason else "VALIDATED"
prefix = "quarantine" if reason else "validated"
day = datetime.now(timezone.utc).strftime("%Y/%m/%d")
dest_key = f"{prefix}/{partner}/{day}/{filename}"

s3.copy({"Bucket": bucket, "Key": key}, bucket, dest_key) # managed, handles large objects
s3.delete_object(Bucket=bucket, Key=key)

try:
audit.put_item(
Item={
"pk": event["id"], # EventBridge event ID makes duplicate deliveries harmless
"partner": partner,
"source_key": key,
"dest_key": dest_key,
"status": status,
"reason": reason or "",
"bytes": head["ContentLength"],
"etag": head["ETag"].strip('"'),
"processed_at": datetime.now(timezone.utc).isoformat(),
},
ConditionExpression="attribute_not_exists(pk)",
)
except ClientError as e:
if e.response["Error"]["Code"] != "ConditionalCheckFailedException":
raise

sns.publish(
TopicArn=TOPIC_ARN,
Subject=f"[{status}] {partner}/{filename}"[:100],
Message=json.dumps({"partner": partner, "file": filename, "status": status, "reason": reason}),
)
return {"status": status}
A few notes on the choices:
  • Size and ETag come from  head_object , not from the event. Rename events don't carry  bytes  or  etag , and asking S3 directly works for both event types.
  •  s3.copy  instead of  copy_object , because the managed copy handles objects above the single-request size limit.
  • The Lambda role needs  s3:GetObject ,  s3:PutObject , and  s3:DeleteObject  on the bucket,  dynamodb:PutItem  on the audit table,  sns:Publish  on the topic, and the KMS permissions for the bucket key.
  • Settings: something like 256 MB memory and a timeout of a few minutes is a reasonable start for CSV feeds; tune from real file sizes.
  • This is a starting point, not a finished product. Validate with your real schemas, add row-level or checksum checks if the feed includes a trailer or manifest, and write tests before you trust it with production money.

Step 6: Make it resilient

EventBridge delivers events at least once, and Lambda can fail for boring reasons (a throttle, a KMS hiccup, a timeout). Four small things make the pipeline dependable:
  1. Idempotency. The "object is gone" check plus the audit row keyed on the EventBridge event ID means a duplicate or retried event does no harm.
  1. A dead-letter destination for async failures. EventBridge invokes Lambda asynchronously, so configure retries and an on-failure destination:  aws lambda put-function-event-invoke-config \ --function-name settlement-validator \ --maximum-retry-attempts 2 \ --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:<region>:<account-id>:settlement-dlq"}}' 
  1. An alarm on the queue. A CloudWatch alarm on  ApproximateNumberOfMessagesVisible > 0  for the DLQ turns silent failures into a page.
  1. A reconciliation sweep. Belt and braces: a scheduled Lambda that lists  inbound/  for objects older than, say, 30 minutes and re-drives them. If an event is ever missed, the file isn't stranded.

Step 7: Test it end to end

sftp -i ~/.ssh/acme_key acme-payments@s-xxxxxxxxxxxxxxxxx.server.transfer.<region>.amazonaws.com
sftp> put settlement_2026-11-01.csv # a good file
sftp> put settlement_missing_header.csv # a file missing required columns
What to check afterwards:
  • The good file is under  validated/acme/<date>/  and gone from  inbound/acme/ .
  • The bad file is under  quarantine/acme/<date>/ , and an SNS message states the reason.
  • The DynamoDB table has one row per file, with status and reason.
  • CloudWatch Logs show the invocation, and the DLQ is empty.
  • From the partner's side, they see only  / , never the bucket name.

Security checklist

  • Key-based auth only for partner users, one key pair per partner, and a documented rotation process.
  • VPC endpoint plus security groups to allow-list partner IPs where you can.
  • Logical home directories so partners never see the bucket or each other.
  • One IAM role per partner, scoped to one prefix, upload-only unless they genuinely need more.
  • SSE-KMS and TLS-only bucket policy.
  • Structured logging and CloudTrail on, with alarms on repeated auth failures.
  • S3 Versioning (and Object Lock if your compliance regime requires immutability) on the buckets that hold audit-relevant files.

What it costs

The part to budget for is the always-on endpoint. In US East (N. Virginia), Transfer Family charges $0.30 per hour for each enabled protocol (roughly $216 to $219 a month for a single SFTP endpoint running 24/7) plus $0.04 per GB uploaded or downloaded. That hourly charge applies whether or not any file moves. EventBridge, Lambda, DynamoDB, and SNS usage at settlement-file volumes is usually small by comparison, and S3 is billed at standard rates. Managed workflows, SFTP connectors, and web apps carry their own pricing. Check the  Transfer Family pricing page  for your Region before you commit, because rates vary by Region and can change.
For a handful of partners sending a few files a day, the fixed endpoint cost dominates, which is the main reason to look at alternatives if your volume is tiny.

Gotchas worth knowing

  • Temp-file-then-rename clients emit rename events, not upload events. Handle both, as in Step 4.
  • At-least-once delivery. Design for duplicates, and add a reconciliation sweep for the rare missed event.
  • Event fields differ by event type. Upload events use  file-path ; rename events use  renamed-file-path  (and  original-file-path ). Don't assume  bytes  or  etag  exist on every event.
  • Partial uploads surface as  SFTP Server File Upload Failed  with a  PARTIAL_UPLOAD  failure code. Alert on them; the partner usually needs to resend.
  • Large files: keep validation to cheap checks and a header read, and push heavy processing to a downstream job.
  • You pay for the endpoint 24/7. If a feed is occasional, consider whether SFTP connectors (you pulling from the partner) or a different transfer mechanism fits better.

Where to take it next

  • Fan out from  validated/  to a Step Functions workflow, a Glue job, or a COPY into your warehouse. EventBridge makes adding consumers a rule change rather than a code change.
  • Add antivirus or content scanning before promoting files out of  inbound/ .
  • Use SFTP connectors for the opposite direction, pulling files from partner-hosted servers. Connectors emit their own EventBridge events (for example  SFTP Connector File Retrieve Completed ), so the same pattern applies.
  • Provide partners with a status page or webhook driven from the audit table.

Wrapping up

The whole design comes down to one idea: let the SFTP layer tell you when something happened, instead of asking the filesystem every few minutes. Transfer Family gives you a managed, per-partner-isolated endpoint, S3 gives you durable storage, EventBridge turns upload completion into a routable event, and a small Lambda decides whether a file is good enough to move on. There's no polling loop, no patching, and the audit trail comes with the design instead of being bolted on later.

AWS Reference Documentation

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