Download the code from here.
In this first example, we're going to implement the photo-sharing app using S3 signed URLs. Here, we'll build on the same mechanisms that we discussed in the Serverless example app chapter, but we'll focus on how to make it more performant.
By the end of this chapter, we'll have a solution that takes advantage of browser as well as proxy caches and serves everything from a single domain, saving clients an additional round of DNS resolution and TLS handshake.
First, we'll focus on downloads, as this area is offers more room for improvement and is more visible to users. Uploads are expected to take some time, but downloads should happen as fast as possible.
Looking at a signed URL it's easy to see why by default they can't be cached:
https://d37lcb86ynk7iq.cloudfront.net/images/C2kJ9lBQCr8
?X-Amz-Algorithm=AWS4-HMAC-SHA256
&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD
&X-Amz-Credential=ASIAUB3O2I
&X-Amz-Date=20230920T101526Z
&X-Amz-Expires=900
&X-Amz-Security-Token=IQoJb3J
&X-Amz-Signature=14aff4d9c4059
&X-Amz-SignedHeaders=host
&x-id=GetObject
Notice the X-Amz-Date
, which is the timestamp of the signature time in seconds precision. It means that two signed URLs for the same image created only a second apart will be different. And since browsers cache based on the full path, they will treat the two URLs as different images and will download them twice.
The timestamp is an essential part of how expiration works, so it can not be removed. A possible solution is to round the signing time back in time so that at least for URLs signed for the same image not far apart will have the same timestamps.
For example, turning the clock back to the last 5-minutes mark yields a URL like this one: