This post will be helpful for those who use CloudFront with some API (API Gateway, AppSync, custom endpoint) hosted in a single region.
In this scenario, the client first interacts with CloudFront in the closest region, and then traffic through the regular network reaches the region where the API is located:
This may take time if you are far from another network.
The most reliable approach is to make a multi-regional API, i.e., host your API in different regions. But if for some reason you can't do that yet, there's a trick that can make things a little better.
Origin Shield
From AWS documentation:
CloudFront Origin Shield adds an additional layer in the CloudFront caching infrastructure that helps to minimize your origin’s load, improve its availability, and reduce its operating costs. By enabling CloudFront Origin Shield, you get the following benefits:
Better cache hit ratio – all requests from all of CloudFront’s caching layers to your origin go through Origin Shield, increasing the likelihood of a cache hit.
Reduced origin load – Origin Shield consolidates content requests for the same object to reduce the number of simultaneous requests.
Better network performance – When you enable Origin Shield in the AWS Region that has the lowest latency to your origin, you can get better network performance.
The last paragraph is what interests us. From the description, it follows that it should now work like this:
Configuration
You can enable Origin Shield through the AWS Console in your Origin settings + choose the region closest to your API:
We use the following template for Serverless Framework:
Origins:
- Id: YourID
OriginShield:
Enabled: true
OriginShieldRegion: ${aws:region}
CloudFormation documentation.
Testing
I configured two different CloudFronts to use the same API, but in one case with Origin Shield, and the other without
Without Origin Shield (1 thread * 100 requests):
With Origin Shield:
Without Origin Shield (4 thread * 50 requests):
With Origin Shield:
As we can see in this use case, the Origin Shield solution is a bit faster!
Caveats
- Using Origin Shield is not free. Check pricing before usage:
- Synthetic tests say nothing about how they will work in your conditions, so do not believe blindly, but test with your data first.
Thanks!
Top comments (3)
Thanks, that’s exactly what I was looking for!
Thank you Roman! Gonna update my AWS config now
Wow! You saved my time! Thank you!