iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
↗️

Absorbing Traffic Spikes with Message Queues for Stable Throughput Control

に公開
2025/12/31

Introduction

When requests are concentrated in a short period of time—such as when user actions trigger a simultaneous surge in processing—subsequent APIs or external services may hit rate limits, leading to 429 errors.

It is ideal to avoid situations where a sudden influx of requests leads to hitting service quotas or rate limits by passing them directly to downstream processes. In this article, we will use a message queue as a buffer to stabilize the processing rate.

We will build a setup that uses Amazon SQS as a buffer to control the concurrency of Lambda functions, and then send 100 requests almost simultaneously. We will use CloudWatch metrics to verify that the parallelism of the downstream processing is kept constant.

Objectives

  • Buffer sudden large spikes in requests using SQS.
  • Limit the number of concurrent Lambda executions to keep downstream processing at a constant rate (building a stable system).

Architecture

We will test this using the following configuration.
We will call the APIGW endpoint almost simultaneously using a for loop in curl.
Because requests arrive all at once, if we weren't buffering, the instances of the Lambda function ② would all spin up instantly. However, this time, we will control the setup so that a maximum of 10 instances run simultaneously by configuring the trigger for the Lambda function from SQS.

Expected Behavior

1. Producer Lambda

Receives the request, sends it to SQS immediately, and terminates. High-speed response.

2. SQS

Created as a standard queue in this demo.
Buffers messages. Large amounts of messages may accumulate during spikes, but they are processed gradually.

3. Consumer Lambda

Concurrency is limited to 10 by the SQS trigger. Processing proceeds at a constant rate.

Implementation

Directory Structure and Terraform Resources

Directory Structure

sqs-buffering-demo/
├── terraform/
│   ├── main.tf
│   ├── variables.tf
│   └── outputs.tf
└── lambda/
    ├── producer/
    │   └── index.py
    └── consumer/
        └── index.py

Terraform

# terraform/main.tf
terraform {
  required_version = ">= 1.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

# SQS Queue
resource "aws_sqs_queue" "main" {
  name                       = "${var.prefix}-queue"
  visibility_timeout_seconds = 180
}

# IAM Role for Producer Lambda
resource "aws_iam_role" "producer_role" {
  name = "${var.prefix}-producer-role"
  
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Principal = {
        Service = "lambda.amazonaws.com"
      }
    }]
  })
}

resource "aws_iam_role_policy_attachment" "producer_basic" {
  role       = aws_iam_role.producer_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_iam_role_policy" "producer_sqs" {
  name = "sqs-send-policy"
  role = aws_iam_role.producer_role.id
  
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect = "Allow"
      Action = [
        "sqs:SendMessage"
      ]
      Resource = aws_sqs_queue.main.arn
    }]
  })
}

# Producer Lambda
data "archive_file" "producer" {
  type        = "zip"
  source_file = "${path.module}/../lambda/producer/index.py"
  output_path = "${path.module}/producer.zip"
}

resource "aws_lambda_function" "producer" {
  filename         = data.archive_file.producer.output_path
  function_name    = "${var.prefix}-producer"
  role            = aws_iam_role.producer_role.arn
  handler         = "index.lambda_handler"
  runtime         = "python3.12"
  source_code_hash = data.archive_file.producer.output_base64sha256
  
  environment {
    variables = {
      QUEUE_URL = aws_sqs_queue.main.url
    }
  }
}

# API Gateway
resource "aws_api_gateway_rest_api" "api" {
  name = "${var.prefix}-api"
}

resource "aws_api_gateway_resource" "submit" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  parent_id   = aws_api_gateway_rest_api.api.root_resource_id
  path_part   = "submit"
}

resource "aws_api_gateway_method" "post" {
  rest_api_id   = aws_api_gateway_rest_api.api.id
  resource_id   = aws_api_gateway_resource.submit.id
  http_method   = "POST"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "lambda" {
  rest_api_id             = aws_api_gateway_rest_api.api.id
  resource_id             = aws_api_gateway_resource.submit.id
  http_method             = aws_api_gateway_method.post.http_method
  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.producer.invoke_arn
}

resource "aws_api_gateway_deployment" "api" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  
  depends_on = [
    aws_api_gateway_integration.lambda
  ]
}

resource "aws_api_gateway_stage" "prod" {
  deployment_id = aws_api_gateway_deployment.api.id
  rest_api_id   = aws_api_gateway_rest_api.api.id
  stage_name    = "prod"
}

resource "aws_lambda_permission" "apigw" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.producer.function_name
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_api_gateway_rest_api.api.execution_arn}/*/*"
}

# IAM Role for Consumer Lambda
resource "aws_iam_role" "consumer_role" {
  name = "${var.prefix}-consumer-role"
  
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Principal = {
        Service = "lambda.amazonaws.com"
      }
    }]
  })
}

resource "aws_iam_role_policy_attachment" "consumer_basic" {
  role       = aws_iam_role.consumer_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_iam_role_policy" "consumer_sqs" {
  name = "sqs-receive-policy"
  role = aws_iam_role.consumer_role.id
  
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect = "Allow"
      Action = [
        "sqs:ReceiveMessage",
        "sqs:DeleteMessage",
        "sqs:GetQueueAttributes"
      ]
      Resource = aws_sqs_queue.main.arn
    }]
  })
}

# Consumer Lambda
data "archive_file" "consumer" {
  type        = "zip"
  source_file = "${path.module}/../lambda/consumer/index.py"
  output_path = "${path.module}/consumer.zip"
}

resource "aws_lambda_function" "consumer" {
  filename                       = data.archive_file.consumer.output_path
  function_name                  = "${var.prefix}-consumer"
  role                          = aws_iam_role.consumer_role.arn
  handler                       = "index.lambda_handler"
  runtime                       = "python3.12"
  timeout                       = 30
  source_code_hash              = data.archive_file.consumer.output_base64sha256
}

# SQS Trigger
resource "aws_lambda_event_source_mapping" "sqs_trigger" {
  event_source_arn = aws_sqs_queue.main.arn
  function_name    = aws_lambda_function.consumer.arn
  batch_size       = 1
  scaling_config {
    maximum_concurrency = 10
  }
}
# terraform/variables.tf
variable "aws_region" {
  description = "AWS Region"
  type        = string
  default     = "ap-northeast-1"
}

variable "prefix" {
  description = "Resource name prefix"
  type        = string
  default     = "sqs-buffering"
}
# terraform/outputs.tf
output "api_endpoint" {
  description = "API Gateway endpoint URL"
  value       = "${aws_api_gateway_stage.prod.invoke_url}/submit"
}

output "queue_url" {
  description = "SQS Queue URL"
  value       = aws_sqs_queue.main.url
}
Commands
Deployment
terraform init
terraform plan
terraform apply
Cleanup
terraform destroy

Lambda (Producer)

A simple function that just sends received requests to SQS.

lambda/producer/index.py
import json
import boto3
import os

sqs = boto3.client('sqs')
QUEUE_URL = os.environ['QUEUE_URL']

def lambda_handler(event, context):
    body = json.loads(event.get('body', '{}'))
    
    sqs.send_message(
        QueueUrl=QUEUE_URL,
        MessageBody=json.dumps(body)
    )
    
    return {
        'statusCode': 202,
        'body': json.dumps({'message': 'Accepted'})
    }

SQS

We are using a standard queue. Key configurations are as follows:

visibility_timeout_seconds

The Visibility Timeout is the time during which a message remains invisible to other consumers after being received.

In this example, the Consumer Lambda's timeout is set to 30 seconds.

To ensure that the function has enough time to process the batch of each record, set the source queue's visibility timeout to at least six times the function's timeout configuration.
Reference: https://docs.aws.amazon.com/lambda/latest/dg/services-sqs-configure.html

AWS official documentation recommends setting the queue's visibility timeout to six times the function's timeout. Therefore, the SQS timeout value is set to 180 seconds.

Other parameters (message retention period, maximum message size, etc.) use default settings.

Lambda (Consumer)

Receives messages from SQS one by one for processing.
We simulate a scenario where this Lambda calls another API or performs some kind of processing by introducing a 5(s) delay.

lambda/consumer/index.py
import json
import time

def lambda_handler(event, context):
    message = json.loads(event['Records'][0]['body'])
    print(f'Processing: {message}')
    
    # Simulate some processing for about 5 seconds
    time.sleep(5)
    
    print(f'Completed: {message}')
    return {'statusCode': 200}

timeout: 30

This value must be set to be shorter than the SQS visibility timeout (180 seconds in this case).
The Lambda function timeout is set to 30 seconds.

batch_size: 1 (SQS Trigger configuration)

The batch size for the Event Source Mapping is set to 1.
We set it to 1 here so that it is easy to confirm "Concurrency = Actual Parallel Processing Count".
This ensures that each Lambda invocation processes only one message.

Controlling Concurrency via SQS Trigger

If there are many messages accumulated in the queue, Lambda instances are spun up simultaneously.

In this case, we limit the maximum number of simultaneously running Lambda instances to 10 by configuring the trigger for the Consumer Lambda from SQS.

This ensures that even if a large number of messages are published from the Producer Lambda to SQS during a spike, downstream processing continues steadily at a constant parallel rate.

Verification

1. Generating a Spike

We send 100 requests all at once.

API_ENDPOINT=$(terraform output -raw api_endpoint)

for i in {1..100}; do
  curl -X POST $API_ENDPOINT \
    -H "Content-Type: application/json" \
    -d "{\"id\": $i, \"timestamp\": \"$(date +%s)\"}" &
done
wait

echo "100 requests sent!"

2. Verification via SQS Console

Open AWS Console → SQS → sqs-buffering-queue, and you can see the number of messages increasing rapidly.

①: Immediately after curl execution

When checked, it showed 78 messages stored in the queue.

②: After waiting a few seconds from ①

Checking again after a short wait, you can confirm that the number of messages is gradually decreasing.
About half are gone.

③: Near completion

Most have been processed.

④: Processing complete

All 100 requests have been processed.
We confirmed that the number of messages stored in the queue is 0.

3. Verifying Concurrency with CloudWatch Metrics

Lambda (Consumer)

Checking the ConcurrentExecutions metric for the target function (sqs-buffering-consumer) in CloudWatch > Lambda.

Looking at the metrics, you can see that it plateaus at 10.

This is because the number of Lambda instances running simultaneously is limited to a maximum of 10 by the trigger configuration when starting Lambda from SQS.

Even when a spike occurs, while messages keep accumulating in SQS, downstream processing proceeds steadily at a constant parallel rate.

Lambda (Producer)

Just to be sure, let's also check the concurrency of the Lambda that was publishing messages.
The metrics show 100, which is the same as the number of calls made by curl.

Summary

By using SQS as a buffer, we can build a stable system where subsequent processes run at a constant rate even if spike-like requests arrive.

I believe SQS buffering is effective for scenarios where downstream calls to GenAI APIs might otherwise hit service quotas (external API calls, DB writes, etc.).

However, although not covered here, when using SQS standard queues, I think it is necessary to design with idempotency and DLQ settings in mind. I would like to incorporate those in my design when applying this in production environments.

References

Discussion