Home > Software engineering >  Continuous cache-misses from Cloudfront when using HTML img tag, but getting cache-hits with Postman
Continuous cache-misses from Cloudfront when using HTML img tag, but getting cache-hits with Postman

Time:01-28

I have a Cloudfront distribution with a S3 origin bucket (using Cloudformation/SAM to delegate resources) that's acting strangely. The S3 bucket only stores images.

Whenever I request an image through the src attribute, the network tab in dev-tools shows that the Cloudfront resource was a cache-miss (remains even after repeated refreshing). However, when sending a GET request through Postman or a browser, after one refresh I start seeing Cache-hits from the respective request sender.

Client-side, I'm using React with styled-components for the image tag. No query strings are being appended and Cloudfront has been told to disregard them as well.

Not sure if this is an issue with my Cloudformation setup or an issue with cached responses from the server, but any guidance would be much appreciated!

My template.yaml file:

UserAssetsDistributionIdentity:
    Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
    Properties:
      CloudFrontOriginAccessIdentityConfig: 
        Comment: 'Origin identity.'
  UserAssetsDistribution: 
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins: 
          - DomainName: // Domain name removed
            Id: user-assets-bucket
            S3OriginConfig: 
              OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${UserAssetsDistributionIdentity}'
        Enabled: 'true'
        Comment: Projects microservice to distribute user uploaded assets
        DefaultCacheBehavior: 
          AllowedMethods:
            - GET
            - HEAD
          CachedMethods: 
            - GET
            - HEAD
          CachePolicyId: b2884449-e4de-46a7-ac36-70bc7f1ddd6d
          TargetOriginId: user-assets-bucket
          ViewerProtocolPolicy: allow-all
        ViewerCertificate:
          AcmCertificateArn: // arn removed
          SslSupportMethod: sni-only
          MinimumProtocolVersion: TLSv1
        Aliases: 
          - uploads.phazia.com
  UserAssetsBucket:
    Type: AWS::S3::Bucket
    Properties: 
      AccessControl: PublicRead

CodePudding user response:

The issue was Chrome caching response headers for repeat-requests to resources.

Devtools shows a status code of 200 for the requested resource along with a (from disk cache) message- led me to believe that the status code AND the response headers were being cached. Tried clearing the browser cache and got the expected Cloudfront header.

  •  Tags:  
  • Related