Amazon CloudFront with Amazon API Gateway Routing using Key Value Store

Amazon CloudFront → CloudFront function → Amazon API Gateway 1 → Amazon API Gateway 2

Route traffic dynamically between API Gateway endpoints using CloudFront Functions and Key Value Store without redeploying infrastructure.

This pattern demonstrates how to use Amazon CloudFront with CloudFront Functions to dynamically route traffic between multiple Amazon API Gateway endpoints.
The routing decisions are based on values stored in CloudFront Key Value Store, allowing for flexible, configuration-driven request routing without redeploying your infrastructure.
This example uses an equal (50:50 distribution) between both API Gateways, showcasing how to implement cell partitioning for your applications.
The pattern deploys a CloudFront distribution, CloudFront Function, CloudFront Key Value Store, and two API Gateway endpoints.

< Back to all patterns

GitHub icon Download this pattern (.zip)

GitHub icon View this pattern on GitHub


Clone repo

git clone https://github.com/aws-samples/serverless-patterns/cd serverless-patterns/cloudfront-keyvaluestore-apigw-routing/typescript/cdk

Deploy

Clone the repository: git clone https://github.com/aws-samples/serverless-patternsChange directory: cd cloudfront-keyvaluestore-apigw-routing/typescript/cdkInstall dependencies: npm installDeploy the CDK stack: cdk deploy


Testing

1. Get Key Value Store ETAG: aws cloudfront-keyvaluestore describe-key-value-store --kvs-arn=[KVSTOREARN]
2. Add entries to the Key Value Store: aws cloudfront-keyvaluestore update-keys --kvs-arn=[KVSTOREARN] --if-match=[ETAG] --puts '[{"Key": "APIGW1URL", "Value": "[APIGATEWAY1URL]"},{"Key": "APIGW2URL", "Value": "[APIGATEWAY2URL]"}]'
3. Access CloudFront URL: curl -i -L [CLOUDFRONTDOMAINNAME]
4. The request should be redirected to either API Gateway 1 or API Gateway 2, showing a response like {"message": "Hello from API 1"} or {"message": "Hello from API 2"}
5. Make multiple requests to observe routing between the two API Gateway endpoints.

Cleanup

Delete the stack: cdk destroy

Created by:

Marco Jahn

Marco Jahn

As a Senior Solutions Architect at Amazon Web Services, Marco helps organizations transform their business through cloud-native architectures and serverless technologies. With over 25 years of hands-on experience in software engineering and architecture, he specializes in Event-Driven Architectures and Domain-Driven Design, guiding customers to build scalable and resilient solutions. Before joining AWS, Marco spent 15+ years as a technical consultant across various industries, working with ISVs and SaaS providers to tackle complex architectural challenges.