Sub topic 4
Publishing custom events with PutEvents
This chapter covers how an application sends its own events to an EventBridge event bus with the PutEvents API. It assumes you know AWS accounts, regions, the AWS CLI, JSON, and basic IAM. You should also know the event envelope from the earlier chapter and have seen the difference between the default bus and a custom bus.
What PutEvents does
PutEvents is the API call a producer uses to send one or more events to an event bus. A producer is any code that emits events, such as a web service, a Lambda function, or a script. The bus then evaluates its rules against each event and delivers matches to targets.
AWS services publish their own events to the default bus automatically. Your application does not get that for free. To emit an event such as OrderPlaced, your code must call PutEvents.
A call to PutEvents is a batch. Each item in the Entries list is a separate event. EventBridge processes the entries independently, so one bad entry does not stop the others.
The fields of an entry
Each entry maps onto the event envelope. These are the fields you set.
| Field | Required | Meaning |
|---|---|---|
| `Source` | Yes | Who produced the event. Use a reverse-DNS style name such as `com.example.orders`. |
| `DetailType` | Yes | A short label for the kind of event, such as `OrderPlaced`. |
| `Detail` | Yes | The event payload, as a JSON object encoded in a string. |
| `EventBusName` | No | The bus name or ARN. If you omit it, the event goes to the default bus. |
| `Resources` | No | A list of ARNs the event concerns. |
| `Time` | No | The event timestamp. If omitted, EventBridge uses the time it received the event. |
| `TraceHeader` | No | An X-Ray trace header, for tracing across services. |
Two points cause most beginner errors. First, Detail is a string, not a nested object. The API expects the JSON document serialized as text. Second, if you forget EventBusName, the event silently goes to the default bus. No error appears, but your rules on the custom bus never see it.
The Source value cannot start with aws.. That prefix is reserved for AWS services, and entries that use it fail.
Publishing with the AWS CLI
First create a custom bus. Then publish one event to it.
aws events create-event-bus --name orders-bus
aws events put-events --entries '[{"Source":"com.example.orders","DetailType":"OrderPlaced","Detail":"{\"orderId\":\"1001\",\"amount\":250,\"status\":\"new\"}","EventBusName":"orders-bus"}]'The Detail value holds escaped quotes because it is JSON inside JSON. On a shell this quoting is easy to get wrong. For anything beyond a quick test, put the entries in a file and pass --entries file://entries.json. The Detail string still has to be escaped inside the file, but you avoid the shell quoting layer.
A successful call returns a response like this:
{
"FailedEntryCount": 0,
"Entries": [
{ "EventId": "11710aed-b79e-4468-a20b-bb3c0c3b4860" }
]
}Each entry in the response lines up with the entry at the same position in the request. A successful entry has an EventId. A failed entry has an ErrorCode and an ErrorMessage instead.
Publishing with boto3
In application code, you call the same API through an SDK. The important habit is checking FailedEntryCount.
import json
import boto3
events = boto3.client("events")
response = events.put_events(
Entries=[
{
"Source": "com.example.orders",
"DetailType": "OrderPlaced",
"Detail": json.dumps({"orderId": "1001", "amount": 250, "status": "new"}),
"EventBusName": "orders-bus",
}
]
)
if response["FailedEntryCount"] > 0:
for entry in response["Entries"]:
if "ErrorCode" in entry:
print(entry["ErrorCode"], entry["ErrorMessage"])json.dumps produces the string that Detail needs, so you never hand-escape quotes in code.
Partial failure and retrying
Because entries succeed or fail independently, a response can be mixed. Suppose you send three entries and the second has malformed Detail. The response has FailedEntryCount of 1, and the second item in Entries carries an error. The first and third events were accepted.
Common error codes include:
InvalidArgument: a required field is missing orDetailis not valid JSON.MalformedDetail: theDetailstring could not be parsed as JSON.InternalFailure: a transient service problem on the EventBridge side.ThrottlingException: you exceeded the request rate for your account and region.
Treat these differently. Validation errors will fail again with the same input, so retrying wastes effort. Fix the event or log it for inspection. Transient errors such as InternalFailure and throttling are worth retrying with backoff.
When you retry, resend only the failed entries, not the whole batch. Otherwise the accepted events are delivered twice. Matching positions in the response to positions in the request gives you the failed subset.
import json
import time
import boto3
events = boto3.client("events")
RETRYABLE = {"InternalFailure", "ThrottlingException"}
def publish(entries, max_attempts=4):
pending = entries
for attempt in range(max_attempts):
response = events.put_events(Entries=pending)
if response["FailedEntryCount"] == 0:
return []
retry, dropped = [], []
for entry, result in zip(pending, response["Entries"]):
if "ErrorCode" not in result:
continue
if result["ErrorCode"] in RETRYABLE:
retry.append(entry)
else:
dropped.append((entry, result))
for entry, result in dropped:
print("not retrying:", result["ErrorCode"], result["ErrorMessage"])
if not retry:
return [e for e, _ in dropped]
pending = retry
time.sleep(2 ** attempt * 0.2)
return pendingThe function returns the entries it could not deliver, so the caller can decide where to store them.
Limits that shape your code
These limits matter when you design a producer:
- Up to 10 entries per call. To send more events, make more calls.
- 256 KB per entry. The size counts
Source,DetailType,Detail,Resources,Time, andEventBusName. A whole request is also capped at 1 MB in some SDK paths, so keep batches well under that. - Account and region quotas on rate. The default quota for
PutEventsvaries by region. Check Service Quotas for your numbers and request an increase if you need one.
If you need to attach a large payload, do not put it in Detail. Store the data in S3 and put the object key in the event. Consumers then fetch the data when they need it. This keeps events small and keeps rule matching fast.
Batching reduces the number of API calls and the latency cost per event. But a batch is not atomic. Do not group events that must succeed or fail together.
Permissions for the producer
The caller needs events:PutEvents permission on the target bus. A minimal identity-based policy looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "events:PutEvents",
"Resource": "arn:aws:events:us-east-1:123456789012:event-bus/orders-bus"
}
]
}Scope Resource to the specific bus ARN. A producer for orders should not be able to write to every bus in the account. If the producer lives in another account, the bus also needs a resource policy that allows it. That is covered in the permissions and cross-account chapters.
Common mistakes
- Passing
Detailas an object. The SDK rejects it or the CLI sends bad JSON. Serialize it to a string. - Omitting
EventBusName. The event lands on the default bus and your custom bus rules never fire. - Ignoring
FailedEntryCount. Events are dropped without any exception. - Using an
aws.prefix inSource. The entry is rejected. - Retrying the whole batch. Accepted events are delivered twice.
- Putting field values in the wrong place. Rules can match
sourceanddetail-typeat the top level and fields insidedetail. If you placeamountinResourcesinstead ofDetail, a pattern ondetail.amountwill never match.
An event that is accepted but matches no rule is not an error. PutEvents reports success, and the event is simply not delivered anywhere. If you expect delivery and see none, check the pattern, the bus name, and the rule's state before you suspect the publisher.
Checking that publishing works
After you publish, confirm the event reached the bus and matched a rule. The Invocations and MatchedEvents CloudWatch metrics on a rule show whether matches occurred. The PutEvents metrics in the AWS/Events namespace, such as SuccessfulRequestLatency and FailedEntries, track the publisher side. To see an event's content, add a rule that sends all events from your source to a CloudWatch Logs group while you develop. Later chapters cover testing patterns and monitoring in more detail.
Exercise
A service calls PutEvents with three entries. The call returns without raising an exception, but FailedEntryCount is 1 and the second item in Entries has ErrorCode MalformedDetail. Which events were delivered, and what should the service do next?
Show answer
The first and third events were accepted, because entries succeed or fail independently. The second event was rejected. MalformedDetail is a validation error, so retrying the same entry will fail again. The service should fix the Detail string (it must be valid JSON serialized as text) or log the entry for inspection. It should not resend the whole batch, because that would deliver the first and third events twice.
Exercise
You publish an OrderPlaced event with Source com.example.orders but omit EventBusName. Your rule on orders-bus never fires, and PutEvents reports no failure. Why, and how do you fix it?
Show answer
Without EventBusName, the event goes to the default bus, not orders-bus. The call is valid, so no error is returned. Add "EventBusName": "orders-bus" to the entry (or the bus ARN), or create a rule on the default bus if that is where you want to match.