Hands-On: Publish Your Own Events

Emit business events from your app and route them with a rule.

1 min read

Your own events make services loosely coupled. NoteSnap's summarizer just announces SummaryCreated, and anyone interested can add a rule later without touching the summarizer's code.

Try it

publish_event.py
import json
import boto3

events = boto3.client("events")

resp = events.put_events(Entries=[{
    "EventBusName": "notesnap",          # a custom bus for your app's events
    "Source": "notesnap.summarizer",     # use your own namespace, never "aws.*"
    "DetailType": "SummaryCreated",
    "Detail": json.dumps({
        "noteId": "notes/todo.txt",
        "userId": "sam",
        "wordCount": 212,
    }),
}])

print("Failed entries:", resp["FailedEntryCount"])

Create the bus and a rule that sends long notes to a Lambda function:

Terminal
aws events create-event-bus --name notesnap

aws events put-rule --name long-summaries --event-bus-name notesnap           --event-pattern '{"source":["notesnap.summarizer"],"detail":{"wordCount":[{"numeric":[">",200]}]}}'

aws events put-targets --rule long-summaries --event-bus-name notesnap           --targets 'Id=notify,Arn=arn:aws:lambda:us-east-1:123456789012:function:notify-user'
Note

Like API Gateway, EventBridge needs permission to invoke your Lambda (aws lambda add-permission with principal events.amazonaws.com). The console adds this automatically.

Watch out

Always check FailedEntryCount in the put_events response. The call can succeed overall while individual entries fail.

Key takeaways

  • put_events publishes your app's events with your own source namespace.
  • Rules on a custom bus route them, so new consumers need no producer changes.
  • Check FailedEntryCount, and grant EventBridge permission to invoke targets.

Check your understanding

Pick an answer to see the explanation.

  1. 1. Why publish events instead of calling the notify service directly?