Skip to content
WritingArticle
  • #serverless
  • #aws
  • #eventbridge
  • #sqs
  • #architecture

Event-Driven Serverless on AWS: EventBridge, SQS, SNS and Step Functions Explained with One Example

Pawan Joshi

6 min read

Share

Most beginner serverless apps are a chain of direct calls: the API calls a function, which calls another function, which calls a third. It works until one step is slow or fails, and then the whole request fails with it.

Event-driven architecture fixes that. Instead of telling other parts of the system what to do, a service announces what happened ("an order was placed") and moves on. Other services react on their own time.

Here's how to do it on AWS, using one example from start to finish.

The example: a workshop registration system

When a student registers for a workshop, the system must:

  1. Save the registration.
  2. Send a confirmation email.
  3. Add the student to the attendee sheet for organizers.
  4. Issue a certificate after the workshop.

The registration API should respond instantly. The email, sheet and certificate can happen a few seconds later, and a failure in one shouldn't affect the others.

The four tools, and when to use each

ServiceUse it whenThink of it as
Amazon EventBridgeMany consumers care about the same business event, with filtering by contentA router for events
Amazon SQSOne consumer must process every message, at its own pace, with retriesA to-do list that absorbs spikes
Amazon SNSYou need fast fan-out to many subscribers, including email, SMS or mobile pushA loudspeaker
AWS Step FunctionsSteps must happen in order, with waits, branches and error handlingA workflow conductor

A common, solid combination: EventBridge routes events to SQS queues, and each queue feeds one Lambda function. EventBridge decides who should hear about an event. SQS makes sure each consumer gets every message, retries failures, and protects downstream systems from spikes.

The design

  1. The registration Lambda writes to DynamoDB, then publishes a RegistrationCreated event to an EventBridge bus and returns 201.
  2. EventBridge rules match that event and send it to two SQS queues: one for emails, one for the attendee sheet.
  3. Each queue triggers its own Lambda consumer.
  4. Failed messages go to a dead-letter queue (DLQ) after a few attempts, so nothing is lost silently.
  5. After the workshop, a scheduled Step Functions workflow issues certificates in batches, waits for rate limits, and records results.

Publishing an event

The producer only knows the event, not who consumes it:

import { EventBridgeClient, PutEventsCommand } from "@aws-sdk/client-eventbridge";
const events = new EventBridgeClient({});
 
export async function publishRegistration(registration) {
  await events.send(new PutEventsCommand({
    Entries: [{
      EventBusName: process.env.BUS_NAME,
      Source: "workshops.registrations",
      DetailType: "RegistrationCreated",
      Detail: JSON.stringify({
        registrationId: registration.id,
        workshopId: registration.workshopId,
        email: registration.email,
        occurredAt: new Date().toISOString(),
      }),
    }],
  }));
}

Tomorrow you can add a "send a WhatsApp reminder" consumer without changing this code at all. That's the real benefit: loose coupling.

Wiring it with AWS SAM

Resources:
  WorkshopBus:
    Type: AWS::Events::EventBus
    Properties:
      Name: workshop-bus
 
  EmailDLQ:
    Type: AWS::SQS::Queue
 
  EmailQueue:
    Type: AWS::SQS::Queue
    Properties:
      VisibilityTimeout: 60          # at least 6x the function timeout is a good rule
      RedrivePolicy:
        deadLetterTargetArn: !GetAtt EmailDLQ.Arn
        maxReceiveCount: 5           # after 5 failed attempts, move to the DLQ
 
  EmailQueuePolicy:
    Type: AWS::SQS::QueuePolicy
    Properties:
      Queues: [!Ref EmailQueue]
      PolicyDocument:
        Statement:
          - Effect: Allow
            Principal: { Service: events.amazonaws.com }
            Action: sqs:SendMessage
            Resource: !GetAtt EmailQueue.Arn
 
  RegistrationToEmail:
    Type: AWS::Events::Rule
    Properties:
      EventBusName: !Ref WorkshopBus
      EventPattern:
        source: [workshops.registrations]
        detail-type: [RegistrationCreated]
      Targets:
        - Arn: !GetAtt EmailQueue.Arn
          Id: email-queue
 
  SendEmailFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs22.x
      Architectures: [arm64]
      Handler: email.handler
      CodeUri: src/
      Timeout: 10
      Events:
        FromQueue:
          Type: SQS
          Properties:
            Queue: !GetAtt EmailQueue.Arn
            BatchSize: 10
            FunctionResponseTypes: [ReportBatchItemFailures]

Repeat the queue, rule and function for the attendee sheet. Each consumer gets its own queue and DLQ, so a broken sheet integration never delays emails.

Three reliability patterns you must use

1. Idempotency: handle the same message twice

SQS and EventBridge deliver at least once. Occasionally a message arrives twice. Your consumer must produce the same result either way, so a student never gets two certificates.

A simple approach is a conditional write to DynamoDB keyed by the event ID:

import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
const db = new DynamoDBClient({});
 
async function firstTime(eventId) {
  try {
    await db.send(new PutItemCommand({
      TableName: process.env.IDEMPOTENCY_TABLE,
      Item: { pk: { S: eventId }, expiresAt: { N: String(Math.floor(Date.now() / 1000) + 86400) } },
      ConditionExpression: "attribute_not_exists(pk)",
    }));
    return true;
  } catch (error) {
    if (error.name === "ConditionalCheckFailedException") return false;   // already processed
    throw error;
  }
}

Turn on DynamoDB TTL on expiresAt so old keys clean themselves up. Powertools for AWS Lambda also has a ready-made idempotency utility.

2. Partial batch failures: don't retry the whole batch

Lambda reads SQS messages in batches. Without care, one bad message makes the whole batch retry. With ReportBatchItemFailures, you report only the failed messages:

export const handler = async (event) => {
  const batchItemFailures = [];
  for (const record of event.Records) {
    try {
      const message = JSON.parse(record.body);
      const registration = message.detail;          // EventBridge puts the payload in "detail"
      if (await firstTime(message.id)) await sendConfirmation(registration);
    } catch (error) {
      console.error(JSON.stringify({ messageId: record.messageId, error: error.message }));
      batchItemFailures.push({ itemIdentifier: record.messageId });
    }
  }
  return { batchItemFailures };
};

3. Dead-letter queues: never lose a message silently

After maxReceiveCount attempts, SQS moves a message to the DLQ. Add a CloudWatch alarm on the DLQ's ApproximateNumberOfMessagesVisible so someone knows. When you've fixed the bug, use SQS redrive to move the messages back to the main queue.

Choreography vs orchestration

What we built with EventBridge is choreography: each service reacts to events independently. It's flexible and loosely coupled.

Some processes need orchestration: a defined order, waits, and a clear picture of where each item is. Issuing certificates is like that:

  1. Fetch attendees who checked in.
  2. For each one, generate a PDF, then email it.
  3. Wait between batches to respect the email provider's rate limit.
  4. Record success or failure for each attendee.

Step Functions is the right tool here. You get retries with backoff per step, a visual history of every run, and no glue code to track state. A good rule: use events between services, and workflows inside a process.

Observability for event-driven systems

When work is spread across services, you need to follow it:

  • Include a correlation ID in every event and log it everywhere.
  • Use structured JSON logs so you can search by that ID in CloudWatch Logs Insights.
  • Turn on AWS X-Ray tracing to see the path across services.
  • Alarm on DLQ depth, consumer errors and queue age (ApproximateAgeOfOldestMessage), which tells you when consumers fall behind.

Key takeaways

  • Publish facts ("RegistrationCreated"), not commands, so new consumers don't require producer changes.
  • EventBridge routes, SQS buffers and retries, SNS fans out fast, and Step Functions orchestrates ordered steps.
  • Every consumer must be idempotent, report partial batch failures, and have a DLQ with an alarm.

Next: store data for systems like this efficiently in DynamoDB Single-Table Design for Beginners. New to serverless? Start with What Is Serverless?