Terraform AWS Rate Limit by Bearer Token

Recently, at October Health, we needed to rate limit some of the services in our new AWS environment by Bearer token. The environment is all terraform, which made it slightly more challenging.

The below terraform snippet will limit unique Bearer tokens (authorization header) to 3000 requests every 5 minutes (around 5 per second).

Terraform Example

 rule {
    name     = "AWS-RateLimitByBearerToken"
    priority = 70 

    action {
      block {}
    }

    statement {
      rate_based_statement {
        limit              = 3000
        aggregate_key_type = "CUSTOM_KEYS"
        custom_key {
            header {
                name = "Authorization"
                text_transformation {
                    priority = 0
                    type     = "MD5"
                }
            }
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "RateLimitByBearerToken"
      sampled_requests_enabled   = true
    }
  }