Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 16

Serverless Stream Processing with Kinesis and Lambda

Recommended resources

Hello! Welcome back to our course on preparing for the AWS Certified Data Engineer - Associate exam.

In our last lesson, we focused on ensuring data gets into your Kinesis stream reliably by diagnosing and resolving throughput bottlenecks like "hot shards." Now that your data is flowing smoothly into the stream, the next logical step is to process it.

This lesson addresses the learning outcome: Process Kinesis streams using AWS Lambda, including Dead-Letter Queue (DLQ) configuration. We will explore how to build a serverless processing pipeline using AWS Lambda, which is a powerful and common pattern for real-time data applications. More importantly, we'll dive deep into the critical topic of error handling to ensure your pipeline is resilient and doesn't get stuck on bad data.

1. The Kinesis-Lambda Integration: Event Source Mapping

The component that connects a Kinesis Data Stream to an AWS Lambda function is called an Event Source Mapping (ESM). You don't interact with the stream directly from your Lambda in the same way you would with an SDK; instead, the ESM acts as a managed poller and event broker.

The ESM is responsible for:

  • Polling each shard in your Kinesis stream for new records.
  • Batching these records together. You can control the batch size and a batching window.
  • Invoking your Lambda function synchronously with a batch of records.
  • Checkpointing, which means it automatically keeps track of the last successfully processed record in each shard. This relieves you of the complex task of state management.
  • Handling retries when your function fails.

This serverless integration simplifies the consumer side of your streaming architecture significantly.

Process Amazon Kinesis Data Streams using AWS Lambda | Amazon Web Services

To see this architecture in action, watch the beginning of this official AWS video, 'Process Amazon Kinesis Data Streams using AWS Lambda'. It provides a great overview of the solution and the role of the event source mapping.

Watch the video from the beginning until 2:22. Focus on the explanation of the event source mapping and its key responsibilities like checkpointing, retries, and batching.


2. Building a Kinesis-Processing Lambda Function

Let's look at the practical aspects of creating a Lambda function that processes Kinesis records.

When the Event Source Mapping invokes your function, it passes an event object that contains a list of records. Your function code needs to iterate through this list. A crucial detail is that the actual data payload within each Kinesis record is Base64 encoded. Your code must decode this data before you can work with it.

The video you just watched continues with a full walkthrough of creating the necessary components: the Kinesis stream, a DynamoDB table to store the results, and the Python Lambda function itself.

Process Amazon Kinesis Data Streams using AWS Lambda | Amazon Web Services

Now, let's continue with the same video to see how to build and configure the Lambda function.

Watch from 2:22 to the end of the video (7:19). Pay close attention to these key steps: IAM Permissions (3:30): The role needs permissions to read from Kinesis (kinesis:*) and write to the destination (in this case, dynamodb:*). Lambda Code (3:55): Notice how the code iterates through event['Records'] and, most importantly, uses base64.b64decode() to access the message data. Adding the Trigger (5:18): This is where the Event Source Mapping is configured in the Lambda console, linking the Kinesis stream to the function.

This simple setup works perfectly as long as every record can be processed successfully. But what happens when things go wrong?


3. The Challenge: Blocking Retries and "Poison Pills"

The default error handling behavior of the Kinesis-Lambda integration is robust but can cause significant problems if not configured correctly.

When your Lambda function fails to process a batch (by timing out or throwing an unhandled exception), the Event Source Mapping treats the entire batch as a failure. It will then retry invoking the function with the exact same batch of records. This retry process will continue until the function succeeds or until the records in the batch expire from the stream (the default data retention is 24 hours).

This creates a blocking scenario. A single malformed record—a "poison pill"—can cause the entire batch to fail repeatedly, preventing the processor from moving on to new records in that shard. This can halt your real-time data processing for hours.

Kinesis-Lambda Batch Reprocessing on Exception
This diagram illustrates the problem. An exception caused by a single record (the 83rd) forces the entire batch of 200 records to be re-processed, halting forward progress and potentially causing duplicate processing of the first 82 records.

The following video explains this critical behavior and introduces the modern solutions.

AWS Lambda: Ultimate Guide to Error Handling

This clip from the 'AWS Lambda: Ultimate Guide to Error Handling' video provides a clear explanation of the blocking retry problem and why it's so important to manage it.

Watch from 2:39 to 7:40. The speaker does an excellent job explaining why letting a function error on a Kinesis batch is a bad idea and the real-world consequences of a blocked stream.


4. Configuring Resilient Error Handling

To prevent a single bad record from blocking your entire pipeline, you must configure the error handling settings on the Event Source Mapping. These settings give you fine-grained control over the retry behavior and provide a way to safely isolate failed records.

Key Configuration Options:

  • On-Failure Destination (DLQ): This is the most important setting. You can configure an Amazon SQS queue or an Amazon SNS topic as a destination for batches that have failed processing. After exhausting all retries, the ESM sends a message containing details about the failed batch to this destination, allowing the stream to continue processing new records.
  • Maximum Retry Attempts: Instead of retrying indefinitely, you can specify a finite number of retries (e.g., 3). After the last attempt fails, the batch is sent to the on-failure destination if one is configured.
  • Bisect Batch on Function Error: When a batch fails, this setting instructs the ESM to split the batch in half and retry each half separately. This process repeats, quickly isolating the specific "poison pill" record that is causing the failure. This is highly recommended.
  • Maximum Record Age in Seconds: You can configure the ESM to discard records that have been in the stream for too long, sending them to the DLQ if configured.

The following AWS documentation provides the definitive guide to these settings.

Retain discarded batch records for a Kinesis Data Streams ...

The official AWS Lambda documentation, 'Retain discarded batch records for a Kinesis Data Streams ...', details exactly how to configure these error handling features.

Read the first three sections of this document, down to 'Security best practices for Amazon S3 destinations'. Focus on: The description of how Lambda retries 'During invocation'. The steps and required IAM permissions (sqs:SendMessage or sns:Publish) for configuring an on-failure destination. The example AWS CLI command for update-event-source-mapping, which shows how to set MaximumRetryAttempts and the DestinationConfig.

It's important to remember that for stream-based sources like Kinesis and DynamoDB Streams, these error handling settings are on the Event Source Mapping, not on the Lambda function's general configuration (which applies to asynchronous sources like S3 or SNS).

Kinesis Data Stream Processing with Lambda and SQS DLQ
This diagram shows the complete, resilient architecture. The Lambda function processes records from the Kinesis stream, and any failed records are sent to an SQS Dead-Letter Queue for later analysis, preventing the stream from getting blocked.
Test your understanding!

You have a Lambda function processing a Kinesis stream. You notice that a single malformed record has caused processing on one shard to stop for over an hour. New records are being added to the stream, but your Lambda consumer is not processing them.

What two settings on the Event Source Mapping should you configure to prevent this from happening in the future?

Show answer
  1. On-Failure Destination: Configure an SQS queue or SNS topic as a destination for failed batches. This ensures that after a set number of retries, the problematic batch is moved out of the main processing path, unblocking the shard.
  2. Maximum Retry Attempts: Set a reasonable number of retries (e.g., 2 or 3). This prevents the ESM from retrying indefinitely and ensures the failing batch is sent to the on-failure destination in a timely manner. Enabling Bisect Batch on Function Error is also a best practice to help isolate the bad record.

5. What's in the DLQ Message?

When a batch is sent to an SQS or SNS on-failure destination, the message does not contain the original data payloads. Instead, it contains metadata about the failed batch, including:

  • streamArn
  • shardId
  • startSequenceNumber and endSequenceNumber
  • The error message (functionError)

You must use this metadata to build a separate process (e.g., another Lambda function) that can fetch the original records from the Kinesis stream using the GetRecords API before they expire. This is a critical point for the exam. If you configure S3 as a destination, Lambda will send the full payload.

The AWS documentation you read earlier also provides examples of these payloads. Take a moment to review them.

Retain discarded batch records for a Kinesis Data Streams ...

Let's revisit the same AWS documentation to see the structure of the message that lands in your DLQ.

Quickly read the section 'Example Amazon SNS and Amazon SQS invocation record'. Note the fields available in the KinesisBatchInfo object. Acknowledge that the actual record data is not present.


Conclusion

In this lesson, you've learned how to build a robust, serverless pipeline to process real-time data from Kinesis Data Streams using AWS Lambda.

Key Takeaways:

  • The Event Source Mapping (ESM) is the managed component that connects Kinesis to Lambda, handling polling, batching, and checkpointing.
  • By default, a function failure causes a blocking retry of the entire batch, which can be halted by a single "poison pill" record.
  • To build a resilient pipeline, you must configure the ESM's error handling with an On-Failure Destination (DLQ), a limited number of Maximum Retry Attempts, and ideally enable Bisect Batch on Function Error.
  • When using SQS or SNS as a DLQ, the message contains only metadata. You must write a separate process to retrieve the original records from the stream before they expire.

You now have a comprehensive understanding of both ingesting data into Kinesis and processing it in a scalable and resilient way.

In our next lesson, we will begin a new module on Apache Kafka. We will compare Amazon MSK with Kinesis for streaming data ingestion scenarios, helping you understand when to choose one powerful streaming service over the other.