Transforming Streaming Data with Lambda and Spark
This lesson explains how streaming records are cleaned, enriched or aggregated with AWS Lambda or Apache Spark, and how the choice depends on whether the transformation is stateless or stateful.
Learning outcomes
After completing this lesson, you will be able to:
- Implement stateless transformations with Lambda.
- Implement stateful transformations with Spark Structured Streaming.
- Keep one feature definition consistent across batch and streaming.
Stateless transformations with Lambda
A stateless transformation handles each record on its own: parsing JSON, dropping invalid records, masking a field, adding a lookup value or converting units. Lambda suits this work in two ways. Firehose data transformation invokes a function with batches of records during delivery; the function returns each record with a result of Ok, Dropped or ProcessingFailed. A Kinesis event source mapping invokes a function with batches read from each shard, with settings for batch size, batching window, parallelisation factor, bisect on error and on-failure destinations.
# Firehose transformation Lambda: drop test events and mask e-mail addresses
import base64, json
def handler(event, context):
output = []
for rec in event["records"]:
data = json.loads(base64.b64decode(rec["data"]))
if data.get("is_test"):
output.append({"recordId": rec["recordId"], "result": "Dropped", "data": rec["data"]})
continue
data["email"] = "***"
payload = base64.b64encode((json.dumps(data) + "\n").encode()).decode()
output.append({"recordId": rec["recordId"], "result": "Ok", "data": payload})
return {"records": output}Stateless or stateful?
Stateful transformations with Spark Structured Streaming
Stateful transformations need memory of earlier records: rolling averages, sessionisation, deduplication across batches and stream-to-stream joins. Spark Structured Streaming processes streams as a series of small batches over a DataFrame, with window functions, watermarks for late data and checkpoints in S3 for recovery. It runs as AWS Glue streaming jobs (serverless) or on Amazon EMR, and reads from Kinesis or Kafka.
Spark suits teams that already use Spark for batch feature engineering, because the same transformation code can run on historical data and on the stream, reducing training-serving skew. Flink offers lower latency per event, while Spark offers one engine for batch and streaming.
The following diagram compares two separate implementations of a feature, one for training and one for production, with a single shared implementation that removes training-serving skew.

Choosing a transformation engine
The engine for transforming streaming data follows from the complexity of the transformation and the volume of data. Lambda suits simple, stateless changes to each record, such as parsing, filtering or enriching it with a lookup, at moderate volumes. Spark Structured Streaming, in AWS Glue or Amazon EMR, suits heavier transformations, joins with reference data and very high volumes, processed in micro-batches. Apache Flink suits stateful processing with event-time windows and low latency. The following table summarises the choice.
| Transformation | Engine | Reason |
|---|---|---|
| Parse, filter or mask each record during delivery | Lambda in Firehose | No servers, per-record logic |
| Score or enrich each event from a stream | Lambda event source mapping | Simple, scales with shards |
| Windowed aggregates with Spark code reuse | Spark Structured Streaming (Glue or EMR) | Same code for batch and stream |
| Lowest-latency stateful processing | Managed Service for Apache Flink | Per-event processing with checkpoints |
Choose the engine
One feature definition for batch and streaming
A recommendation team computes "items viewed per user in the last hour" with PySpark for training. In production, a Lambda function computes the same feature differently, and offline accuracy is much higher than online accuracy.
The gap is training-serving skew: the two implementations disagree on edge cases such as late events and time zones. Moving the streaming computation to a Glue streaming job that reuses the same PySpark window function, with an event-time watermark, gives one definition for both paths. Writing the results to SageMaker Feature Store means training reads the offline store and inference reads the online store, both produced by the same code.
How can per-record clean-up happen while Firehose delivers data?
Show answer
With a Firehose Lambda transformation, which processes each batch of records before delivery.
Exam Tips
Remember for the exam
- Per-record cleanup during delivery: Firehose Lambda transformation.
- Stateful windows and joins: Spark Structured Streaming or Flink.
- Reusing batch Spark code on streams reduces training-serving skew.
- Lambda event source mappings control batch size, parallelisation and failure handling.
- Watermarks decide how long to wait for late events.