3: Data Operations and Support

    Automating Data Processing with AWS Services

    Automation in an AWS data pipeline is the contract between an event (a file landed, a clock ticked, a queue grew) and a deterministic action (load a partition, run an aggregation, refresh a materialized view). The lowest-cost, fastest-glue layer for those actions is AWS Lambda, scheduled or triggered by Amazon EventBridge, with state and audit kept in Amazon CloudWatch Logs. This section walks through how AWS data engineers wire those pieces together: when AWS Lambda is the right runtime versus when control belongs in AWS Step Functions or Amazon MWAA, what shape aggregation and pivoting take when written in AWS Lambda or SQL, and how to configure Amazon CloudWatch Logs so that the resulting automation is observable without manual log scraping.

    The default mistake is to push too much compute into AWS Lambda. AWS Lambda excels at lightweight per-record reactions: a PutObject event triggers a function that registers a new partition, advances a watermark in Amazon DynamoDB, or invokes the AWS Glue StartJobRun API. It does not excel at multi-hour transforms, at high-fan-in joins across terabytes of Parquet, or at orchestrating dozens of sibling steps. Each AWS Lambda invocation is capped at 15 minutes of execution and 10 GB of memory, with a payload limit of 6 MB synchronous and 256 KB asynchronous. The correct mental model is to let AWS Lambda be the trigger and the gate, not the engine. The actual transform runs in AWS Glue Spark, Amazon EMR, Amazon Redshift, or Amazon Athena, and AWS Lambda calls those services through the AWS SDK.

    The second mistake is to schedule jobs through cron-style logic embedded in AWS Lambda itself. The intended path is Amazon EventBridge: EventBridge rules match against event patterns (an aws.glue Job State Change event with state SUCCEEDED) or run on a schedule, and EventBridge Scheduler offers one-shot and recurring schedules with time-zone awareness, flexible time windows, and per-schedule IAM roles. Putting schedule logic in EventBridge means the schedule is visible to AWS CloudTrail, can be modified without code deployments, and can run at scale without consuming AWS Lambda concurrency.

    The third mistake is to leave AWS Lambda functions writing to the default Amazon CloudWatch log group with the default infinite retention. Default infinite retention raises storage cost over the life of a pipeline and makes log analysis slow. The right configuration sets a retention policy through PutRetentionPolicy (commonly 30 or 90 days for application logs, 365 days for audit-relevant logs), groups the logs into a meaningful log group per pipeline (not per function), and sends structured JSON instead of free-text print statements, so that Amazon CloudWatch Logs Insights can query them.

    Skill 3.1.8: Using AWS Lambda to Automate Data Processing

    A canonical pattern is the partition-registration function. An Amazon S3 PutObject event for a new Parquet file fires an Amazon EventBridge rule that targets an AWS Lambda function. The function parses the object key, computes the Apache Hive partition values, and calls the AWS Glue Data Catalog to register the partition.

    import boto3
    import os
    import json
    import re
    
    glue = boto3.client("glue")
    DATABASE = os.environ["GLUE_DATABASE"]
    TABLE = os.environ["GLUE_TABLE"]
    
    KEY_PATTERN = re.compile(
     r"^events/year=(?P<year>\d{4})/month=(?P<month>\d{2})/day=(?P<day>\d{2})/[^/]+\.parquet
    quot;
    ) def lambda_handler(event, context): for record in event["Records"]: bucket = record["s3"]["bucket"]["name"] key = record["s3"]["object"]["key"] match = KEY_PATTERN.match(key) if not match: print(json.dumps({"level": "warn", "msg": "key did not match pattern", "key": key})) continue values = [match["year"], match["month"], match["day"]] location = f"s3://{bucket}/events/year={values[0]}/month={values[1]}/day={values[2]}/" try: glue.create_partition( DatabaseName=DATABASE, TableName=TABLE, PartitionInput={ "Values": values, "StorageDescriptor": { "Location": location, "InputFormat": "org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", "OutputFormat": "org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat", "SerdeInfo": {"SerializationLibrary": "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"}, }, }, ) print(json.dumps({"level": "info", "msg": "registered partition", "values": values})) except glue.exceptions.AlreadyExistsException: print(json.dumps({"level": "info", "msg": "partition already exists", "values": values})) return {"status": "ok"}

    Three configuration choices govern this function in practice. Memory is sized for the JSON overhead and the AWS Glue call latency, usually 256 MB; AWS Lambda scales CPU linearly with memory, so a 256 MB function gets roughly a quarter vCPU. The timeout is set to 30 seconds, leaving headroom over the typical AWS Glue Data Catalog API latency of under a second. Reserved concurrency is set if downstream limits matter; an AWS Glue Data Catalog account-level partition-creation rate above the documented soft limit causes throttling, so a reserved concurrency of 10 caps the function at ten parallel writes.

    📊 Limit: AWS Lambda timeout is capped at 900 seconds. The temporary /tmp directory ranges from 512 MB to 10,240 MB. Synchronous request payload is 6 MB. Asynchronous payload is 256 KB.

    💡 Exam Trap: AWS Lambda invocation modes have different error semantics. Synchronous invocations return errors to the caller and do not retry by default. Asynchronous invocations retry twice with exponential backoff, then send the failure event to the configured on-failure destination or dead-letter queue if neither is set the event is silently dropped after retries. Choose the configuration explicitly, do not rely on defaults.

    ⚠️ Anti-Pattern: Running a multi-step ETL chain inside a single AWS Lambda function with sequential boto3 calls and time.sleep waits. Each step burns billed Lambda time waiting on an external service, and a single retryable failure restarts the entire chain. Use AWS Step Functions for multi-step orchestration so retries, waits, and parallel branches are first-class.

    Skill 3.2.6: Aggregation, Rolling Average, Grouping, and Pivoting

    Aggregation patterns belong in the engine, not in AWS Lambda. AWS Lambda runs the loader, the gate, or the metadata update; the actual GROUP BY, window function, or pivot runs in Amazon Athena, Amazon Redshift, AWS Glue Spark, or Amazon EMR. The decision criterion is the data size and the join surface. For a daily report on a few partitions, Amazon Athena over Apache Parquet is fast and cheap. For a continuous rollup that must serve a dashboard at sub-second latency, an Amazon Redshift materialized view is the right home. For a Spark transformation that walks the full table and writes a new derived table, AWS Glue Spark or Amazon EMR is the engine.

    A rolling 7-day average expressed in Amazon Athena uses standard SQL window functions:

    SELECT
     customer_id,
     event_date,
     SUM(amount) OVER (
     PARTITION BY customer_id
     ORDER BY event_date
     RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW
     ) AS rolling_7d_sum,
     AVG(amount) OVER (
     PARTITION BY customer_id
     ORDER BY event_date
     RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW
     ) AS rolling_7d_avg
    FROM events
    WHERE event_date BETWEEN DATE '2024-01-01' AND DATE '2024-12-31';
    

    A pivot from rows to columns in Amazon Athena uses conditional aggregation rather than a dedicated PIVOT clause:

    SELECT
     region,
     SUM(CASE WHEN channel = 'web' THEN amount ELSE 0 END) AS amount_web,
     SUM(CASE WHEN channel = 'mobile' THEN amount ELSE 0 END) AS amount_mobile,
     SUM(CASE WHEN channel = 'kiosk' THEN amount ELSE 0 END) AS amount_kiosk
    FROM events
    GROUP BY region;
    

    Amazon Redshift offers a native PIVOT operator that produces the same shape with less boilerplate. The choice between the two is driven by where the result is read: an Amazon QuickSight dashboard over Amazon Athena reads the SUM/CASE form fine; a downstream materialized view in Amazon Redshift uses the native PIVOT for consistency with the rest of the warehouse.

    🎯 Scenario: A retail team needs a 30-day moving average of orders per region, refreshed hourly, surfaced in Amazon QuickSight. The pipeline writes raw orders as Apache Parquet on Amazon S3 partitioned by date. The right pattern is an Amazon EventBridge Scheduler that fires hourly, an AWS Lambda function that invokes an Amazon Athena CTAS query writing a rolling-window result to a results table, and a QuickSight dataset that reads that results table directly. Putting the window logic in AWS Lambda Python would consume the AWS Lambda 15-minute ceiling on the larger partitions; pushing it to Amazon Athena keeps the function under a second of execution time.

    Skill 3.3.7: Using Amazon CloudWatch Logs to Log Application Data

    Amazon CloudWatch Logs is where AWS Lambda, AWS Glue, Amazon EMR, Amazon Redshift, and Amazon API Gateway send their logs. The default behaviour is helpful for getting started and expensive for keeping. Three configuration knobs matter at scale. First, retention: every log group should carry an explicit RetentionInDays set through the AWS SDK or AWS CloudFormation. Second, structure: a JSON log line is queryable through CloudWatch Logs Insights; a plain text log line is not, beyond basic substring matching. Third, subscription filters: log groups that feed compliance archives, anomaly detection, or alerting should publish through a subscription filter to Amazon Data Firehose for archival in Amazon S3, or to AWS Lambda for real-time inspection.

    # Set a 90-day retention on a Lambda log group.
    aws logs put-retention-policy \
     --log-group-name "/aws/lambda/de-partition-register" \
     --retention-in-days 90
    
    # Create a metric filter so the pipeline emits a custom metric for error log lines.
    aws logs put-metric-filter \
     --log-group-name "/aws/lambda/de-partition-register" \
     --filter-name "ErrorCount" \
     --filter-pattern '{ $.level = "error" }' \
     --metric-transformations \
     metricName=PartitionRegisterErrors,metricNamespace=DEPipeline,metricValue=1,defaultValue=0
    

    A subscription filter forwards log events into the wider stack:

    aws logs put-subscription-filter \
     --log-group-name "/aws/lambda/de-partition-register" \
     --filter-name "to-firehose" \
     --filter-pattern "" \
     --destination-arn "arn:aws:firehose:us-east-1:111122223333:deliverystream/de-logs-archive" \
     --role-arn "arn:aws:iam::111122223333:role/de-cwl-to-firehose"
    

    The combination of structured JSON, a metric filter for error counts, and a CloudWatch alarm watching that metric replaces the manual log scraping pattern that creeps into pipelines that grew without a logging plan. Alarms route through Amazon SNS to email, Slack via AWS Chatbot, or Amazon Q Developer in chat for on-call escalation.

    💡 Exam Trap: Amazon CloudWatch Logs charges for both ingestion and storage. The Logs ingestion rate is the dominant cost driver at scale. Functions that emit a debug-level log line per record at high throughput must either downgrade those lines to a sample, drop them entirely under normal operation, or route through Amazon Data Firehose for cheaper bulk archive.

    ⚠️ Anti-Pattern: Configuring every log group with infinite retention "for compliance." The compliance requirement is almost always retention of a specific subset, not the entire firehose. Set explicit retention per log group, and route the actual compliance copy to Amazon S3 with the appropriate AWS Lake Formation governance and AWS Key Management Service encryption.

    Decision Anchor. Choose AWS Lambda as the automation glue when the work is event-driven, completes inside 15 minutes, and fits a single function. Choose AWS Step Functions when the work spans more than two steps, needs retry-with-backoff, parallel branches, or human approval. Choose Amazon MWAA when the work is a DAG with cross-team operators, Apache Airflow-native sensors, or a complex backfill pattern.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the AWS - Data Engineer Associate learning hub.