AWS SAM: MinimumCompressionSize property doesn't work on Lambda responses for AWS::Serverless::Api

204 Views Asked by At

According to the AWS SAM Template Documentation, you can specify a MinimumCompressedSize attribute for AWS::Serverless::API resources which should compress response bodies which exceed a given threshold, yet in local testing this doesn't work.

Take for instance a slightly modified node v16 "Hello-World" project generated using sam init:

template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app
  Globals:
  Function:
    Timeout: 3
    MemorySize: 128
Resources:
  CompressedApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: "Prod"
      MinimumCompressionSize: 0
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api 
          Properties:
            Path: /hello
            Method: get
            RestApiId: !Ref CompressedApi

And the corresponding node code for app.lambdaHandler:

exports.lambdaHandler = async (event, context) => {
    try {
        // const ret = await axios(url);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
                // location: ret.data.trim()
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

After running sam local start-api and opening 127.0.0.1:3000/hello I should expect (if my browser sends an Accept-Encoding header with gzip, deflate, or identity compression) to see a compressed response, even for a small payload of 25 bytes since my MinimumCompressionSize is set to zero.

Instead I get a uncompressed response:

enter image description here

Why doesn't the lambda function response get compressed? Did I make some mistake in composing this template.yaml?

Note: I'm aware it's possible to setup gzip compression using an HttpApi resource (instead of the Api type used here) by having the lambda function itself compress the response body using a process like the one described in this blog post, but my understanding is that this type of Api resource should support this out-of-the-box and there's some mistake I'm making in setting up my application.

0

There are 0 best solutions below