Build highly available streams with Amazon Kinesis Data Streams
Architectural choice is really a trade-off between replication lag and operational simplicity. The postโs warm versus cold standby split is less about Kinesis itself and more about where you want the failover cost to land: in always-on duplicate capacity, or in the orchestration required to bring consumers back online fast enough to meet the target RTO. For teams running streaming pipelines, that distinction affects shard planning, Lambda concurrency, deployment automation, and the amount of cross-Region duplication you are willing to absorb.
The replication path introduces its own reliability envelope. Using a Lambda-based replicator with enhanced fan-out keeps cross-Region copying from competing directly with normal consumption, but it also creates a second failure domain that must be observed and tuned. Iterator age, retry behavior, and batch failure handling become more than metrics; they are the leading indicators of whether the secondary Region can actually serve as a credible recovery target. If replication falls behind, the business may still have a live stream, but not a usable recovery point.
Failover and failback are operational workflows, not just API calls. Switching producer endpoints, restarting consumers in the secondary Region, and choosing a safe starting position all raise the risk of duplicate or overlapping records downstream. That makes sink design important: idempotent writes, retention sizing, and replay tolerance are part of the architecture, not an afterthought. The post also highlights a practical point for production teams: failback is often safer when treated as a controlled, manual procedure rather than an automatic reversal, especially when state synchronization and consumer lag need to be verified first.
Many use cases are moving towards a real-time data strategy due to demand for real-time insights, low-latency response times, and the ability to adapt to the changing needs of end-users. For this type of workload, you can use
Considerations for high availability
Before we dive into our example use case, there are several considerations to keep in mind when designing a highly available Kinesis Data Streams workload that relate to the business need for a particular pipeline:- Recovery Time Objectiveย (RTO) is defined by the organization. RTO is the maximum acceptable delay between the interruption of service and restoration of service. This determines what is considered an acceptable time window when service is unavailable.
- Recovery Point Objectiveย (RPO) is defined by the organization. RPO is the maximum acceptable amount of time since the last data recovery point. This determines what is considered an acceptable loss of data between the last recovery point and the interruption of service.
- Warm standbyย โ An architecture in which there is active replication of data from the Kinesis data stream in Region A to Region B. Consumers of the data stream are running in both Regions at all times. Recommended for use cases that canโt withstand extended downtime past their replication lag.
- Cold standbyย โ Active replication of data from the data stream in Region A to Region B, but consumers of the data stream in Region B are spun up when an outage in Region A is detected. Recommended for use cases that can afford some downtime as infrastructure is spun up in secondary Region. In this scenario, RPO will be similar to the warm standby strategy; however, RTO will increase.
Warm standby pattern
The following architecture diagram illustrates the warm standby high availability pattern for Kinesis Data Streams.
Cold standby pattern
The following architecture diagram illustrates the cold standby high availability pattern for Kinesis Data Streams.
Which pattern makes sense for our use case?
Letโs revisit the use case described earlier to identify which of the strategies best meets our needs. We can extract the pieces of information from the customerโs problem statement to identify that they need a high availability architecture that:- Canโt withstand extended amounts of data loss
- Must resume operations within 15 minutes of service interruption identification
Launch AWS CloudFormation resources
If you want to follow along with our code samples, you can launch the following CloudFormation stack and follow the instructions in order to simulate the cold standby architecture referenced in this post. For purposes of the Kinesis Data Streams high availability setup demo, we useยus-west-2ย as the primary Region andย us-east-2ย as the failover Region. While deploying this solution in your own account, you can choose your own primary and failover Regions.
- Deploy the supplied CloudFormation template in failover Regionย
us-east-2.
us-east-2ย as the value for theย FailoverRegionย parameter in the CloudFormation template.
- Deploy the supplied CloudFormation template in primary Regionย
us-west-2.
us-east-2ย as the value for theย FailoverRegionย parameter in the CloudFormation template.
In steps 1 and 2, we deployed the following resources in the primary and failover Regions:
- KDS-HA-Streamย โ AWS::Kinesis::Stream (primary and failover Region)
- KDS-HA-ProducerLambdaย โ AWS::Lambda::Function (primary Region)
- KDS-HA-ConsumerLambdaย โ AWS::Lambda::Function (primary and failover Region)
- KDS-HA-ReplicationAgentLambdaย โ AWS::Lambda::Function (primary Region)
- KDS-HA-FailoverLambdaย โ AWS::Lambda::Function (primary Region)
- ticker-pricesย โ AWS::DynamoDB::GlobalTable (primary and failover Region)
KDS-HA-Streamย Kinesis data stream is deployed in both Regions. An enhanced fan-out consumer of theย KDS-HA-Streamย stream KDS-HA-ReplicationAgentLambda in the primary Region is responsible for replicating messages to the data stream in the failover Region.
KDS-HA-ConsumerLambdaย is a Lambda function consuming messages out of theย KDS-HA-Streamย stream and persisting data into a DynamoDB table after preprocessing.
You can inspect the content of theย ticker-pricesย DynamoDB table in the primary and failover Region. Note thatย last_updated_regionย attribute showsย us-west-2ย as its value because itโs the primary Region.
Replication
When deciding how to replicate data from a data stream in Region A to a data stream in Region B, there are several strategies that involve a consumer reading data off of the primary stream and sending that data cross-Region to the secondary data stream. This would act as a replicator service, responsible for copying the data between the two streams, maintaining a relatively low latency to replicate and ensuring data isnโt lost during this replication. Because replication off of a shared throughput data stream could impact the flow of data in a production workload, we recommend using theย enhanced fan-outย feature of Kinesis Data Streams consumers to ensure replication doesnโt have an impact on consumption latency. The replication strategy implemented in this post features asynchronous replication, meaning that the replication process doesnโt block any standard data flow in the primary stream. Synchronous replication would be a safer approach to guarantee replication and avoid data loss; however, this isnโt possible without a service-side implementation. The following image shows a timeline of data flow for the cold standby architecture, with data being replicated as soon as itโs published.
Lambda replication
Lambda can treat aย Kinesis data stream as an event source, which will funnel events from your data stream into a Lambda function. This Lambda function then receives and forwards these events across Regions to your data stream in a secondary Region. Lambda functions allow you to utilize best streaming practices such as retries of records that encounter errors, bisect on error functionality, and using the Lambda parallelization factor; using more instances of your Lambda function than you have available shards can help process records faster. This Lambda function is at the crux of the architecture for high availability; itโs responsible solely for sending data across Regions, and it also has the best capability to monitor the replication progress. Important metrics to monitor for Lambda replication includeยIteratorAge, which indicates how old the last record in the batch was when it finished processing. A highย IteratorAgeย value indicates that the Lambda function is falling behind and therefore is not keeping up with data ingestion for replication purposes. A highย IteratorAgeย can lead to a higher RPO and the higher likelihood of data unavailability when a passive failover happens.
We use the following sample Lambda function in our CloudFormation template to replicate data across Regions:
import json
import boto3
import random
import os
import base64
def lambda_handler(event, context):
client = boto3.client("kinesis", region_name=os.environ["FAILOVER_REGION"])
records = []
for record in event["Records"]:
records.append(
{
"PartitionKey": record["kinesis"]["partitionKey"],
"Data": base64.b64decode(record["kinesis"]["data"]).decode("utf-8"),
}
)
response = client.put_records(Records=records, StreamName="KDS-HA-Stream")
if response["FailedRecordCount"] > 0:
print("Failed replicating data: " + json.dumps(response))
raise Exception("Failed replicating data!")
The Lambda replicator in the CloudFormation template is configured to read from the data stream in the primary Region.
The following code contains the necessaryย AWS Identity and Access Managementย (IAM) permissions for Lambda, giving access for the Lambda function to assume this role. All actions are permitted on data streams and DynamoDB. In the principal of least privilege, itโs recommended to restrict this to the necessary streams in a production environment.
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: root
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'kinesis:DescribeStream'
- 'kinesis:DescribeStreamSummary'
- 'kinesis:GetRecords'
- 'kinesis:GetShardIterator'
- 'kinesis:ListShards'
- 'kinesis:ListStreams'
- 'kinesis:SubscribeToShard'
- 'kinesis:PutRecords'
Resource:
- 'arn:aws:kinesis:*:*:stream/KDS-HA-Stream'
- 'arn:aws:kinesis:*:*:stream/KDS-HA-Stream/consumer/KDS-HA-Stream-EFO-Consumer:*'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/CloudWatchLogsFullAccess'
ย
Health check
A generalized strategy for determining when to consider our data stream unavailable involves the use ofย Amazon CloudWatchย metrics. We use the metrics coming off of our Lambda producer and consumer in order to assess the availability of our data stream. While producing to a data stream, an error might appear as one of the following responses back from the data stream:ยPutRecordย orย PutRecordsย returns anย AmazonKinesisException 500ย orย AmazonKinesisException 503ย error. When consuming from a data stream, an error might appear as one of the following responses back from the data stream:ย SubscribeToShard.Successย orย GetRecordsย returns anย AmazonKinesisException 500ย orย AmazonKinesisException 503.
We can calculate our effective error rate based onย PutRecord.Successย andย GetRecord.Success.ย An average error rate of 1% or higher over a time window of 5 minutes, for example, could indicate that there is an issue with the data stream, and we may want to fail over. In our CloudFormation template, this error rate threshold as well as time window are configurable, but by default we check for an error rate of 1% in the last 5 minutes to trigger a failover of our clients.
Client failover
When a data stream is deemed to be unreachable, we must now take action to keep our system available and reachable for clients on both ends of the interaction. This means for producers following the cold standby high availability architecture, we change the destination stream where the producer was writing. If high availability and failover of data producers and consumers isnโt a requirement of a given use case, a different architecture would be a better fit. Prior to failover, the producer may have been delivering data to a stream in Region A, but we now automatically update the destination to be the stream in Region B. For different clients, the methodology of updating the producer will be different, but for ours, we store the active destination for producers in the Lambda environment variables from AWS CloudFormation and update our Lambda functions dynamically on health check failure scenarios. For our use case, we use the maximum consumer lag time (iteratorAge) plus some buffer to influence the starting position of the failover consumer. This allows us to ensure that the consumer in the secondary Region doesnโt skip records that havenโt been processed in the originating Region, but some data overlap may occur. Note that some duplicates in the downstream system may be introduced, and having an idempotent sink or some method of handling duplicates must be implemented in order to avoid duplicate-related isssues.
In the case where data is successfully written to a data stream but is unable to be consumed from the stream, the data will not be replicated and therefore be unavailable in the second Region. The data will be durably stored in the primary data stream until it comes back online and can be read from. Note that if the stream is unavailable for a longer period of time than your total data retention period on the data stream, this data will be lost. Data retention for Kinesis Data Streams can be retrospectively increased up to 1 year.
For consumers in a cold standby architecture, upon failure detection, the consumer will be disabled or shut down, and the same consumer instance will be spun up in the secondary Region to consume from the secondary data stream. On the consumer side, we assume that the consumer application is stateless in our provided solution. If your application requires state, you can migrate or preload the application state viaย Amazon Simple Storage Serviceย (Amazon S3) or a database. For a stateless application, the most important aspect of failover is the starting position.
In the following timeline, we can see that at some point, the stream in Region A was deemed unreachable.
iteratorAgeMilliseconds). This ensures that data isnโt skipped by the consumer application. Keep in mind that there may be some overlap in records in the downstream destinations.
In the provided cold standby AWS CloudFormation example, we can manually trigger a failover with theย AWS Command Line Interfaceย (AWS CLI). In the following code, we manually fail over toย us-east-2:
aws lambda invoke --function-name KDS-HA-FailoverLambda --cli-binary-format raw-in-base64-out --payload '{}' response.json --region us-west-2
After a few minutes, you can inspect the content of theย ticker-pricesย DynamoDB table in the primary and failover Region. Note that theย last_updated_regionย attribute showsย us-east-2ย as its value because itโs failed over to theย us-east-2ย Region.
Failback
After an outage or service unavailability is deemed to be resolved, the next logical step is to reorient your clients back to their original operating Regions. Although it may be tempting to automate this procedure, a manual failback approach during off-business hours when minimal production disruption will take place makes more sense. In the following images, we can visualize the timeline with which consumer applications are failed back to the original Region.
- Re-enable the event source mapping and start consuming messages from the primary Region at the latest position:
aws lambda create-event-source-mapping --function-name KDS-HA-ConsumerLambda --batch-size 100 --event-source-arn arn:aws:kinesis:us-west-2:{{accountId}}:stream/KDS-HA-Stream --starting-position LATEST --region us-west-2
- Switch the producer back to the primary Region:
aws lambda update-function-configuration --function-name KDS-HA-ProducerLambda --environment "Variables={INPUT_STREAM=KDS-HA-Stream,PRODUCING_TO_REGION=us-west-2}" --region us-west-2
- In the failover Region (
us-east-2), wait for your data streamโsยGetRecordsย max iterator age (in milliseconds) CloudWatch metric to report 0 as a value. Weโre waiting for the consumer Lambda function to catch up with all produced messages. - Stop consuming messages from the failover Region.
- Run the following AWS CLI command and grab the UUID from the response, which we use to delete the existing event source mapping. Make sure youโre picking event source mapping for the Lambda functionย
KDS-HA-ConsumerLambda.
aws lambda list-event-source-mappings --region us-east-2
aws lambda delete-event-source-mapping --uuid {{UUID}} --region us-east-2
- Restart the replication agent in the primary Region.
- Run following AWS CLI command, and capture ConsumerARN from the response:
aws kinesis list-stream-consumers --stream-arn arn:aws:kinesis:us-west-2:{{accountId}}:stream/KDS-HA-Stream --region us-west-2
aws lambda create-event-source-mapping --function-name KDS-HA-ReplicationAgentLambda --batch-size 100 --event-source-arn {{ConsumerARN}} --starting-position LATEST --region us-west-2
When this is complete, you can observe the same data stream metricsโthe number of records in and out per second, consumer lag metrics, and number of errors as described in the health check section of this postโto ensure that each of the components has resumed processing data in the original Region. We can also take note of the data landing in DynamoDB, which displays which Region data is being updated from in order to determine the success of our failback procedure.
We recommend for any streaming workload that canโt withstand extended data loss or downtime to implement some form of cross-Region high availability in the unlikely event of service unavailability. These recommendations can help you determine which pattern is right for your use case.
Clean up
To avoid incurring future charges, complete the following steps:- Delete the CloudFormation stack from primary Regionย
us-west-2. - Delete the CloudFormation stack from failover Regionย
us-east-2. - List all event source mappings in primary Regionย
us-west-2ย using theยaws lambda list-event-source-mappings --region us-west-2ย command and note the UUIDs of the event source mappings tied to theยKDS-HA-ConsumerLambdaย andยKDS-HA-ReplicationAgentLambdaย Lambda functions. - Delete event source mappings in primary Region us-west-2 tied to the KDS-HA-ConsumerLambda and KDS-HA-ReplicationAgentLambda Lambda functions using theย
aws lambda delete-event-source-mapping --uuid {{UUID}} --region us-west-2ย command and UUIDs noted in the previous step.
Conclusion
Building highly available Kinesis data streams across multiple Regions is multi-faceted, and all aspects of your RPO, RTO, and operational costs need to be carefully considered. The code and architecture discussed in this post is one of many different architectural patterns you can choose for your workloads, so make sure to choose the appropriate architecture based on the criteria for your specific requirements. To learn more about Kinesis Data Streams, we have aย getting started guideย as well as aย workshopย to walk through all the integrations with Kinesis Data Streams. You can also contact your AWS Solutions Architects, who can be of assistance alongside your high availability journey.About the Authors
Jeremy Ber has been working in the telemetry data space for the past 7 years as a Software Engineer, Machine Learning Engineer, and most recently a Data Engineer. In the past, Jeremy has supported and built systems that stream in terabytes of data per day, and process complex machine learning algorithms in real time. At AWS, he is a Senior Streaming Specialist Solutions Architect supporting both Amazon MSK and Amazon Kinesis. Pratik Patel is a Sr Technical Account Manager and streaming analytics specialist. He works with AWS customers and provides ongoing support and technical guidance to help plan and build solutions using best practices, and proactively helps keep customerโs AWS environments operationally healthy.Enjoyed this article? Sign up for our newsletter to receive regular insights and stay connected.
