Send Messages From a Consumer to AWS Lambda (Complete Guide + Multi-Language Examples)

AWS Lambda can be invoked from many types of “consumers”: scripts, applications, backend services, or event sources like SQS, SNS, or API Gateway. This article shows three main ways to send messages to Lambda:

  1. Direct invoke using AWS SDK (synchronous or asynchronous)
  2. Send a message via Amazon SQS → automatically triggers Lambda
  3. Publish to Amazon SNS → automatically triggers Lambda

Below you will find practical code snippets for all major languages commonly used with Lambda.


1. Architecture Options for Sending Messages to AWS Lambda

Option A — Direct SDK Invocation

The consumer calls Lambda directly with AWS SDK.
✔️ Real-time
✔️ Full control over request/response
❌ Requires IAM credentials

Good for microservices, backend systems, and scheduled jobs.


Option B — SQS → Lambda

The consumer sends a message to SQS, and Lambda is triggered automatically.

✔️ Decoupled architecture
✔️ Auto-retry and DLQ support
❌ Lambda receives messages only as they appear in queue


Option C — SNS → Lambda

The consumer publishes messages to SNS, and SNS invokes Lambda.

✔️ Fan-out (one message → multiple subscribers)
✔️ Fast
❌ No built-in retry persistence like SQS


2. Example: Lambda Function (JavaScript/Node.js)

This is the Lambda function receiving messages:

exports.handler = async (event) => {
  console.log("Event Received:", JSON.stringify(event));

  return {
    statusCode: 200,
    body: "Message processed successfully"
  };
};

Now let’s trigger it from different consumers.


3. Direct AWS Lambda Invocation Examples

3.1 Python (Boto3)

import boto3
import json

lambda_client = boto3.client("lambda", region_name="eu-central-1")

payload = {"message": "Hello from Python!"}

response = lambda_client.invoke(
    FunctionName="myLambdaFunction",
    InvocationType="RequestResponse",  # Or "Event" for async
    Payload=json.dumps(payload)
)

print("Response:", response["Payload"].read().decode())

3.2 Java (Spring Boot + AWS SDK v2)

@Service
public class LambdaService {

    private final LambdaClient lambdaClient = LambdaClient.builder()
            .region(Region.EU_CENTRAL_1)
            .build();

    public String sendToLambda() {
        InvokeRequest request = InvokeRequest.builder()
                .functionName("myLambdaFunction")
                .payload(SdkBytes.fromUtf8String("{\"message\":\"Hello from Java!\"}"))
                .build();

        InvokeResponse response = lambdaClient.invoke(request);
        return response.payload().asUtf8String();
    }
}

3.3 PHP (AWS SDK for PHP)

require 'vendor/autoload.php';

use Aws\Lambda\LambdaClient;

$lambda = new LambdaClient([
    'region' => 'eu-central-1',
    'version' => 'latest'
]);

$result = $lambda->invoke([
    'FunctionName' => 'myLambdaFunction',
    'Payload' => json_encode(['message' => 'Hello from PHP!']),
    'InvocationType' => 'RequestResponse'
]);

echo $result->get('Payload');

3.4 C# (.NET AWS SDK)

using Amazon.Lambda;
using Amazon.Lambda.Model;

var client = new AmazonLambdaClient(Amazon.RegionEndpoint.EUCentral1);

var request = new InvokeRequest
{
    FunctionName = "myLambdaFunction",
    Payload = "{\"message\":\"Hello from C#\"}",
    InvocationType = InvocationType.RequestResponse
};

var response = await client.InvokeAsync(request);

string responseString = System.Text.Encoding.UTF8.GetString(response.Payload.ToArray());
Console.WriteLine(responseString);

4. Triggering Lambda via SQS

4.1 Producer (Python, sends message to SQS)

import boto3
import json

sqs = boto3.client("sqs")

sqs.send_message(
    QueueUrl="https://sqs.eu-central-1.amazonaws.com/123/myqueue",
    MessageBody=json.dumps({"user": "John", "action": "create"})
)

4.2 Lambda receives event

exports.handler = async (event) => {
    for (const record of event.Records) {
        const body = JSON.parse(record.body);
        console.log("Received from SQS:", body);
    }
};

5. Triggering Lambda via SNS

5.1 Publish from JavaScript/Python/Anything

JavaScript example:

const AWS = require("aws-sdk");
const sns = new AWS.SNS();

sns.publish({
  TopicArn: "arn:aws:sns:eu-central-1:123:MyTopic",
  Message: JSON.stringify({ event: "FileUploaded", file: "abc.jpg" })
}).promise();

5.2 Lambda receives SNS event

exports.handler = async (event) => {
    const message = JSON.parse(event.Records[0].Sns.Message);
    console.log("SNS message:", message);
};

6. Triggering Lambda via API Gateway (HTTP POST)

Consumer sends HTTP POST

curl -X POST https://xyz.execute-api.eu-central-1.amazonaws.com/prod/handler \
  -H "Content-Type: application/json" \
  -d '{"message":"Hello via API Gateway!"}'

Lambda receives body

exports.handler = async (event) => {
  console.log("Body:", event.body);
};

7. Best Practices for Sending Messages to Lambda

✔️ Use SQS for reliable processing and retries

✔️ Use SNS for high-fan-out message distribution

✔️ Use direct SDK invocation only when needed

✔️ Always validate event payloads

✔️ Use IAM policies with least privilege

✔️ For high load, enable Lambda concurrency controls


8. More Direct Invocation Examples

8.1 TypeScript (Node.js AWS SDK v3)

import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";

const client = new LambdaClient({ region: "eu-central-1" });

async function callLambda() {
  const input = {
    FunctionName: "myLambdaFunction",
    InvocationType: "Event",
    Payload: Buffer.from(JSON.stringify({ id: 123, action: "ping" })),
  };

  const command = new InvokeCommand(input);
  const response = await client.send(command);

  console.log("Status:", response.StatusCode);
}

callLambda();

8.2 Go (Golang)

package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

func main() {
	cfg, _ := config.LoadDefaultConfig(context.TODO(), config.WithRegion("eu-central-1"))
	client := lambda.NewFromConfig(cfg)

	body, _ := json.Marshal(map[string]string{"msg": "Hello from Go!"})

	result, _ := client.Invoke(context.TODO(), &lambda.InvokeInput{
		FunctionName:   aws.String("myLambdaFunction"),
		Payload:        body,
		InvocationType: types.InvocationTypeRequestResponse,
	})

	fmt.Println(string(result.Payload))
}

8.3 Ruby

require "aws-sdk-lambda"

client = Aws::Lambda::Client.new(region: "eu-central-1")

response = client.invoke(
  function_name: "myLambdaFunction",
  payload: JSON.generate(message: "Hello from Ruby!")
)

puts response.payload.read

8.4 Bash / CLI

aws lambda invoke \
  --function-name myLambdaFunction \
  --payload '{"message":"Hello from CLI"}' \
  response.json

cat response.json

9. More SQS → Lambda Examples

9.1 Java Producer to SQS

SqsClient sqsClient = SqsClient.builder()
        .region(Region.EU_CENTRAL_1)
        .build();

SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
        .queueUrl("https://sqs.eu-central-1.amazonaws.com/123/myqueue")
        .messageBody("{\"orderId\":999}")
        .build();

sqsClient.sendMessage(sendMsgRequest);

9.2 PHP Producer to SQS

$sqs = new Aws\Sqs\SqsClient([
  'region' => 'eu-central-1',
  'version' => 'latest'
]);

$sqs->sendMessage([
  'QueueUrl' => $queueUrl,
  'MessageBody' => json_encode(['item' => 'Book', 'qty' => 2])
]);

9.3 Lambda Processing SQS Batch

exports.handler = async (event) => {
  for (let record of event.Records) {
    const msg = JSON.parse(record.body);
    console.log("Order:", msg);
  }
};

10. More SNS → Lambda Examples

10.1 C# Publish to SNS

using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

var client = new AmazonSimpleNotificationServiceClient();

var request = new PublishRequest
{
    TopicArn = "arn:aws:sns:eu-central-1:123:MyTopic",
    Message = "{\"event\": \"UserRegistered\", \"userId\":123}"
};

await client.PublishAsync(request);

10.2 Lambda receiving SNS

exports.handler = async (event) => {
  const msg = JSON.parse(event.Records[0].Sns.Message);
  console.log("SNS Data:", msg);
};

11. API Gateway → Lambda Examples

11.1 POST Request From Any Consumer

Curl

curl -X POST https://xyz.execute-api.amazonaws.com/prod \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com"}'

JavaScript (fetch)

fetch("https://xyz.execute-api.amazonaws.com/prod", {
  method: "POST",
  body: JSON.stringify({ message: "Hello" }),
});

PHP

$response = file_get_contents(
  "https://xyz.execute-api.amazonaws.com/prod",
  false,
  stream_context_create([
    "http" => [
      "method" => "POST",
      "header" => "Content-Type: application/json",
      "content" => json_encode(["m" => "Hello from PHP"])
    ]
  ])
);

12. Kinesis → Lambda Example

Producer (Python)

import boto3, json

kinesis = boto3.client("kinesis")

kinesis.put_record(
    StreamName="myStream",
    Data=json.dumps({"temperature":22.1}),
    PartitionKey="sensor-1"
)

Lambda receiving Kinesis batch

exports.handler = async (event) => {
  event.Records.forEach(record => {
    const payload = Buffer.from(record.kinesis.data, "base64").toString();
    console.log("Kinesis Data:", payload);
  });
};

13. S3 Event → Lambda Example

Upload triggers Lambda automatically

aws s3 cp file.jpg s3://mybucket/uploads/

Lambda receives event

exports.handler = async (event) => {
  console.log("New file:", event.Records[0].s3.object.key);
};

14. Best Practices (Extended)

Message Routing

  • Use SNS when you need fan-out to multiple Lambdas/services.
  • Use SQS when reliability and retries matter.
  • Use API Gateway when exposing a public API.

Payload Size

  • Lambda direct invoke: 6 MB
  • SQS: 256 KB
  • SNS: 256 KB
  • API Gateway: 10 MB

Security

  • Always restrict IAM:
    • lambda:InvokeFunction
    • sqs:SendMessage
    • sns:Publish

Monitoring

  • CloudWatch Logs
  • X-Ray Tracing
  • Dead Letter Queues (DLQ)

15. Conclusion

Sending a message from any consumer to AWS Lambda is straightforward thanks to the AWS SDKs and event integrations. Whether you choose SDK invocation, SQS, SNS, or API Gateway, the process is flexible and supports all major programming languages.

 

This article is inspired by real-world challenges we tackle in our projects. If you're looking for expert solutions or need a team to bring your idea to life,

Let's talk!

    Please fill your details, and we will contact you back

      Please fill your details, and we will contact you back