Workflow executions by outcome
Step Functions, one execution per file
Project 07 · Serverless on AWS
Point-of-sale systems in 140 stores drop sales files into Amazon S3 throughout the day. Each new file triggers an EventBridge rule that starts a Step Functions workflow: a Lambda function validates the file, and an AWS Glue job merges its rows into an Apache Iceberg table in the Glue Data Catalog. Athena queries the table directly and Redshift Serverless refreshes the reporting views every 15 minutes. Nothing runs between files, so the whole pipeline costs about $14 a day.
Step Functions, one execution per file
From the processed files, 30 days
Per day
Per day, with the alert threshold
Everything the pipeline uses, in USD
p50 and p95 per day
Oct 6, most recent first
Event-driven from end to end: a file arrives, a workflow runs, and then everything scales back to zero.
01 · Land
Amazon S3
POS systems upload about 630 sales files a day to s3://sales-landing/<store>/<date>/.
02 · Trigger
Amazon EventBridge
An Object Created rule starts one Step Functions execution per file.
03 · Validate
AWS Lambda
Checks the header, row count and encoding. Bad files move to a quarantine prefix with the reason.
04 · Transform
AWS Glue
A Spark job types the rows and merges them into an Iceberg table on transaction id.
05 · Catalog
Glue Data Catalog
Every Iceberg commit updates the catalog, so new rows are queryable immediately.
06 · Serve
Athena · Redshift Serverless
Athena for ad hoc questions; Redshift refreshes reporting views every 15 minutes.
transaction_id and sku, so a file processed twice, by a retry or a manual rerun, does not double the sales.Raw files keep their CSV layout; the Iceberg table is what Athena and Redshift query.
s3://sales-landingCSV files from POS systemsstore_id / register_idstringtransaction_idstringsold_atstringsku / quantity / unit_pricestringpayment_typestringcard, cash, gift_card, mobilesales.transactionsIceberg table · Glue Data Catalog · days(sold_at), store_idtransaction_id / skustringstore_idintsold_attimestampquantity / unit_priceint / decimal(10,2)source_filestringpipeline_dailyRollup · the CSV downloaddatedatefiles / executions_*intlambda_invocations / lambda_errorsintglue_p50_s / glue_p95_sintcost_*_usd / sales_usddecimalThe Step Functions workflow, the validation Lambda and the Glue job.
Step Functions workflow (Amazon States Language): validate, transform, and quarantine on failure.
{
"Comment": "Process one POS sales file from S3",
"StartAt": "ValidateFile",
"States": {
"ValidateFile": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "validate-sales-file",
"Payload": {
"bucket.$": "$.detail.bucket.name",
"key.$": "$.detail.object.key"
}
},
"ResultSelector": { "file.$": "$.Payload" },
"Retry": [
{
"ErrorEquals": ["Lambda.TooManyRequestsException", "Lambda.ServiceException"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2
}
],
"Catch": [
{ "ErrorEquals": ["InvalidFile"], "ResultPath": "$.error", "Next": "Quarantine" }
],
"Next": "MergeIntoIceberg"
},
"MergeIntoIceberg": {
"Type": "Task",
"Resource": "arn:aws:states:::glue:startJobRun.sync",
"Parameters": {
"JobName": "merge-sales-file",
"Arguments": {
"--source_key.$": "$.file.key",
"--store_id.$": "$.file.store_id"
}
},
"Retry": [
{
"ErrorEquals": ["Glue.ConcurrentRunsExceededException", "Glue.AWSGlueException"],
"IntervalSeconds": 30,
"MaxAttempts": 4,
"BackoffRate": 2
}
],
"End": true
},
"Quarantine": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "quarantine-sales-file", "Payload.$": "$" },
"Next": "Rejected"
},
"Rejected": {
"Type": "Fail",
"Error": "InvalidFile",
"Cause": "The file failed validation and was moved to quarantine"
}
}
}
Lambda: cheap checks before any Spark runs. Raising InvalidFile sends the execution to the quarantine branch.
import csv
import io
import boto3
s3 = boto3.client("s3")
EXPECTED = ["store_id", "register_id", "transaction_id", "sold_at", "sku", "quantity", "unit_price", "payment_type"]
MAX_BYTES = 50 * 1024 * 1024
class InvalidFile(Exception):
"""A file that must not be processed. Step Functions catches this by name."""
def handler(event, context):
bucket, key = event["bucket"], event["key"] # <store>/<yyyy-mm-dd>/<file>.csv
head = s3.head_object(Bucket=bucket, Key=key)
if head["ContentLength"] == 0:
raise InvalidFile(f"{key} is empty")
if head["ContentLength"] > MAX_BYTES:
raise InvalidFile(f"{key} is larger than 50 MB")
body = s3.get_object(Bucket=bucket, Key=key)["Body"].read()
try:
text = body.decode("utf-8-sig")
except UnicodeDecodeError as err:
raise InvalidFile(f"{key} is not UTF-8: {err}") from err
reader = csv.reader(io.StringIO(text))
header = next(reader, [])
if [h.strip().lower() for h in header] != EXPECTED:
raise InvalidFile(f"{key} has an unexpected header: {header}")
rows = sum(1 for _ in reader)
if rows == 0:
raise InvalidFile(f"{key} has no rows")
return {
"bucket": bucket,
"key": key,
"store_id": key.split("/")[0].removeprefix("store-"),
"rows": rows,
"etag": head["ETag"].strip('"'),
}
Glue job (Spark + Iceberg): type the rows and merge them on transaction_id and sku, so reruns never duplicate sales.
import sys
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from pyspark.sql import functions as F
# Job parameters include --datalake-formats iceberg and the glue_catalog Spark settings.
args = getResolvedOptions(sys.argv, ["JOB_NAME", "source_key", "store_id"])
glue = GlueContext(SparkContext.getOrCreate())
spark = glue.spark_session
job = Job(glue)
job.init(args["JOB_NAME"], args)
rows = (
spark.read.option("header", True).csv(f"s3://sales-landing/{args['source_key']}")
.select(
F.col("store_id").cast("int").alias("store_id"),
"register_id",
"transaction_id",
F.to_utc_timestamp(F.to_timestamp("sold_at"), "America/Chicago").alias("sold_at"),
"sku",
F.col("quantity").cast("int").alias("quantity"),
F.col("unit_price").cast("decimal(10,2)").alias("unit_price"),
"payment_type",
)
.where(F.col("quantity") != 0)
.dropDuplicates(["transaction_id", "sku"])
.withColumn("source_file", F.lit(args["source_key"]))
)
rows.createOrReplaceTempView("incoming")
spark.sql("""
MERGE INTO glue_catalog.sales.transactions AS t
USING incoming AS s
ON t.transaction_id = s.transaction_id AND t.sku = s.sku
WHEN NOT MATCHED THEN INSERT *
""")
job.commit()
On Sep 18 a software update at one store changed the CSV header. Eleven files failed validation and went to quarantine with the reason; every other store's files kept flowing. After the store's export was fixed, the quarantined files were replayed.
Reprocessing a month for an audit hit Glue's concurrent-run limit. Step Functions retried with backoff, so 31 executions finished late instead of failing; p95 Glue time that day was about 7 minutes.
Glue is two-thirds of the cost. Moving backfills to Glue Flex on Sep 27 cut Glue spend by about 6% without slowing the daily files.
Sales are queryable in Athena about six minutes after a store uploads a file, and in the Redshift reporting views within the next 15-minute refresh.
About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as pipeline_daily.csv or read data.json.