Event-Driven Microservices
Test distributed systems locally. Build an SNS/SQS fan-out topology with independent polling services, all on your machine.
The commands below use the real AWS CLI with --endpoint-url; LocalEmu also ships awsemu, a zero-config wrapper that sets it for you.
The Problem
Event-driven microservices are the hardest AWS architectures to test. Each service communicates through messaging (SNS, SQS, EventBridge) and reacts to events asynchronously. Testing the full flow requires:
- All services running simultaneously
- Messaging infrastructure (topics, queues, subscriptions) fully configured
- Each service polling its own queue and reacting independently
- Secrets and configuration available for each service
- A way to publish test events and verify they flow through the entire pipeline
On real AWS, standing this up every test run is impractical (queue + topic + subscription + event-source-mapping propagation alone is minutes), so teams end up sharing a dev account, stepping on each other's resources, and chasing ghost failures from leftover state.
The result: developers test individual services in isolation and hope the integrations work when deployed together. Bugs that only appear in the full flow are discovered in staging or production.
The Solution
LocalEmu lets you create the entire messaging topology locally in seconds. You can build, test, and verify complete event-driven architectures on your laptop before pushing to CI or deploying to AWS.
--> SQS (notification-queue) --> Notification Service --> DynamoDB (notifications)
Walkthrough: Mini E-Commerce System
Before exploring individual patterns, let us build a complete working example. This mini e-commerce system has three services that communicate through SNS and SQS:
Order Service
Accepts orders and publishes events to an SNS topic. Does not know about downstream consumers.
Payment Service
Reads from an SQS queue subscribed to the order topic. Records payment results in DynamoDB.
Notification Service
Reads from a separate SQS queue subscribed to the same topic. Sends order confirmations to customers.
--> SQS (notification-queue) --> Notification Service --> DynamoDB (notifications)
Step 1: Set up all resources
This setup script creates the SNS topic, both SQS queues, subscribes the queues to the topic, and creates the DynamoDB tables. Run it once after starting LocalEmu.
#!/usr/bin/env bash
# Create the SNS topic, SQS queues + subscriptions, and DynamoDB tables for
# the mini e-commerce system. Idempotent: safe to run multiple times.
set -euo pipefail
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_DEFAULT_REGION=us-east-1
ENDPOINT="--endpoint-url=http://localhost:4566"
echo "→ creating SNS topic order-events..."
aws $ENDPOINT sns create-topic --name order-events >/dev/null
echo "→ creating SQS queues payment-queue + notification-queue..."
aws $ENDPOINT sqs create-queue --queue-name payment-queue >/dev/null
aws $ENDPOINT sqs create-queue --queue-name notification-queue >/dev/null
echo "→ subscribing both queues to the topic..."
aws $ENDPOINT sns subscribe \
--topic-arn arn:aws:sns:us-east-1:000000000000:order-events \
--protocol sqs \
--notification-endpoint arn:aws:sqs:us-east-1:000000000000:payment-queue >/dev/null
aws $ENDPOINT sns subscribe \
--topic-arn arn:aws:sns:us-east-1:000000000000:order-events \
--protocol sqs \
--notification-endpoint arn:aws:sqs:us-east-1:000000000000:notification-queue >/dev/null
echo "→ creating DynamoDB tables payments + notifications..."
aws $ENDPOINT dynamodb create-table \
--table-name payments \
--key-schema AttributeName=order_id,KeyType=HASH \
--attribute-definitions AttributeName=order_id,AttributeType=S \
--billing-mode PAY_PER_REQUEST 2>/dev/null || echo " payments already exists"
aws $ENDPOINT dynamodb create-table \
--table-name notifications \
--key-schema AttributeName=order_id,KeyType=HASH \
--attribute-definitions AttributeName=order_id,AttributeType=S \
--billing-mode PAY_PER_REQUEST 2>/dev/null || echo " notifications already exists"
aws $ENDPOINT dynamodb wait table-exists --table-name payments
aws $ENDPOINT dynamodb wait table-exists --table-name notifications
echo "→ all resources ready." Step 2: Order Service
The Order Service publishes order events to the SNS topic. It does not know or care which services consume the events. This is the decoupling that makes event-driven architectures powerful.
"""Order service: publishes order events to SNS.
Knows nothing about downstream consumers (payment, notification, etc.).
"""
from __future__ import annotations
import json
import os
import boto3
def get_client(service: str):
kwargs = {"region_name": "us-east-1"}
endpoint = os.environ.get("AWS_ENDPOINT_URL")
if endpoint:
kwargs["endpoint_url"] = endpoint
return boto3.client(service, **kwargs)
TOPIC_ARN = os.environ.get(
"ORDER_EVENTS_TOPIC_ARN",
"arn:aws:sns:us-east-1:000000000000:order-events",
)
def place_order(order_id: str, customer: str, items: list[str], total: float) -> dict:
sns = get_client("sns")
message = json.dumps(
{
"order_id": order_id,
"customer": customer,
"items": items,
"total": total,
}
)
sns.publish(TopicArn=TOPIC_ARN, Message=message, Subject="new-order")
return {"order_id": order_id, "status": "published"} Step 3: Payment Service
The Payment Service polls its SQS queue, parses the SNS envelope, extracts the order data, and records the payment in DynamoDB.
"""Payment service: polls its SQS queue, records payments in DynamoDB."""
from __future__ import annotations
import json
import os
import boto3
def get_client(service: str):
kwargs = {"region_name": "us-east-1"}
endpoint = os.environ.get("AWS_ENDPOINT_URL")
if endpoint:
kwargs["endpoint_url"] = endpoint
return boto3.client(service, **kwargs)
QUEUE_URL = os.environ.get(
"PAYMENT_QUEUE_URL",
"http://sqs.us-east-1.localhost:4566/000000000000/payment-queue",
)
TABLE_NAME = os.environ.get("PAYMENT_TABLE", "payments")
def process_payments(*, max_messages: int = 10, wait_seconds: int = 0) -> int:
"""Drain the queue once; return number of payments processed."""
sqs = get_client("sqs")
ddb = get_client("dynamodb")
resp = sqs.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=max_messages,
WaitTimeSeconds=wait_seconds,
)
processed = 0
for msg in resp.get("Messages", []):
envelope = json.loads(msg["Body"])
order = json.loads(envelope.get("Message", "{}"))
ddb.put_item(
TableName=TABLE_NAME,
Item={
"order_id": {"S": order["order_id"]},
"amount": {"N": str(order["total"])},
"status": {"S": "charged"},
},
)
sqs.delete_message(QueueUrl=QUEUE_URL, ReceiptHandle=msg["ReceiptHandle"])
processed += 1
return processed Step 4: Notification Service
The Notification Service works the same way but reads from a different queue and writes to a different table. In production this would send an email or push notification. For testing, it records what was sent.
"""Notification service: polls its SQS queue, records notifications sent."""
from __future__ import annotations
import json
import os
import boto3
def get_client(service: str):
kwargs = {"region_name": "us-east-1"}
endpoint = os.environ.get("AWS_ENDPOINT_URL")
if endpoint:
kwargs["endpoint_url"] = endpoint
return boto3.client(service, **kwargs)
QUEUE_URL = os.environ.get(
"NOTIFICATION_QUEUE_URL",
"http://sqs.us-east-1.localhost:4566/000000000000/notification-queue",
)
TABLE_NAME = os.environ.get("NOTIFICATION_TABLE", "notifications")
def send_notifications(*, max_messages: int = 10, wait_seconds: int = 0) -> int:
sqs = get_client("sqs")
ddb = get_client("dynamodb")
resp = sqs.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=max_messages,
WaitTimeSeconds=wait_seconds,
)
sent = 0
for msg in resp.get("Messages", []):
envelope = json.loads(msg["Body"])
order = json.loads(envelope.get("Message", "{}"))
ddb.put_item(
TableName=TABLE_NAME,
Item={
"order_id": {"S": order["order_id"]},
"customer": {"S": order["customer"]},
"type": {"S": "order_confirmation"},
"status": {"S": "sent"},
},
)
sqs.delete_message(QueueUrl=QUEUE_URL, ReceiptHandle=msg["ReceiptHandle"])
sent += 1
return sent Step 5: Test the complete flow
This test publishes an order event and verifies that both downstream queues receive the message with the correct data. Run the setup script first, then run this test.
"""End-to-end integration test for the mini e-commerce system.
Flow:
1. order_service.place_order() publishes to SNS
2. SNS fans out to payment-queue and notification-queue
3. payment_service.process_payments() drains the payment queue, writes DDB
4. notification_service.send_notifications() drains the notification queue, writes DDB
5. Assert both DynamoDB tables have the expected rows.
"""
from __future__ import annotations
import os
import sys
import uuid
import boto3
import pytest
# Make src/ importable
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
os.environ.setdefault("AWS_ENDPOINT_URL", "http://localhost:4566")
os.environ.setdefault("AWS_ACCESS_KEY_ID", "AKIAIOSFODNN7EXAMPLE")
os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
os.environ.setdefault("AWS_DEFAULT_REGION", "us-east-1")
from order_service import place_order # noqa: E402
from payment_service import process_payments # noqa: E402
from notification_service import send_notifications # noqa: E402
KWARGS = {
"endpoint_url": "http://localhost:4566",
"aws_access_key_id": "AKIAIOSFODNN7EXAMPLE",
"aws_secret_access_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"region_name": "us-east-1",
}
@pytest.fixture(scope="session")
def ddb():
return boto3.client("dynamodb", **KWARGS)
def test_order_flows_through_all_services(ddb):
order_id = f"ORD-{uuid.uuid4().hex[:8]}"
# Place an order; the publish happens inside place_order().
result = place_order(
order_id=order_id,
customer=f"{uuid.uuid4().hex[:6]}@example.com",
items=["widget-a", "widget-b"],
total=59.99,
)
assert result == {"order_id": order_id, "status": "published"}
# Drain both queues end-to-end. Long-poll briefly to absorb SNS fan-out latency.
payments = process_payments(wait_seconds=2)
notifications = send_notifications(wait_seconds=2)
assert payments >= 1, f"payment service drained {payments} messages, expected >= 1"
assert notifications >= 1, f"notification service drained {notifications} messages, expected >= 1"
# Verify DynamoDB rows.
p = ddb.get_item(TableName="payments", Key={"order_id": {"S": order_id}}).get("Item")
assert p is not None
assert p["status"]["S"] == "charged"
assert float(p["amount"]["N"]) == 59.99
n = ddb.get_item(TableName="notifications", Key={"order_id": {"S": order_id}}).get("Item")
assert n is not None
assert n["type"]["S"] == "order_confirmation"
assert n["status"]["S"] == "sent" Step 6: Run it
$ ./scripts/setup.sh
→ creating SNS topic order-events...
→ creating SQS queues payment-queue + notification-queue...
→ subscribing both queues to the topic...
→ creating DynamoDB tables payments + notifications...
→ all resources ready.
$ ./scripts/test.sh
collected 1 item
tests/test_ecommerce.py::test_order_flows_through_all_services PASSED
============================== 1 passed in 0.17s ==============================
The full flow, SNS publish, fan-out to both queues, both services drain and write DynamoDB rows, asserted end-to-end, runs in about 170 ms once LocalEmu is warm. No AWS account, no credentials, no cost. The whole project (three services + pytest + setup/teardown scripts) lives in
10-microservices/
of the examples repo.
Architecture Tips
Use dead-letter queues
Always pair your processing queues with DLQs. Test locally that failed messages are redirected correctly by deliberately throwing exceptions in your consumer service.
Test idempotency
SQS guarantees at-least-once delivery. Send the same message twice and verify your handler processes it correctly both times (or deduplicates it). This is easy to test locally, hard to simulate on real AWS.
Script your setup
Put all infrastructure creation commands in a seed script or Terraform configuration. This makes setup reproducible across team members and CI. See the Terraform guide for the full pattern.
Combine with Docker Compose
Run your microservices alongside LocalEmu in Docker Compose. Each service connects to http://localemu:4566 inside the Docker network. See the Local Development guide for the Docker Compose setup.