Programming Search⌘K

Patterncore

Event Message

Also called Event Message pattern, event, event notification, domain event message.

An event message is a message that tells other programs that something happened, such as an order that was placed. The sender reports a fact and does not tell the receivers what to do.

Family
integration
Intent
Tell the programs that care about a change that the change happened, by a message on a channel, so that the sender does not need to know who reacts or how.
Also called
event, event notification

Intent

Tell other programs that something happened, by a message. The book asks: "How can messaging be used to transmit events from one application to another?"12 The answer: "Use an Event Message for reliable, asynchronous event notification between applications."1 The sender reports a fact. It does not tell the receivers what to do with it.

Problem

A shop takes orders. For each order, billing must charge the card, the warehouse must pack the items, and an email service must send a confirmation. If the shop calls each of these programs, the shop must know all of them, and it must change each time that one more program wants to know about orders. When one of them is down, the shop must wait or try again.

The forces are these. The shop knows that an order was placed, but the other programs decide what to do with that fact. A program that is added next year must get the same facts with no change to the shop. And the notice must come soon, because it is about a change that happens now.

Solution

The sender makes a message for each change and puts it on a channel, usually a Publish-Subscribe Channel, so that each program that cares gets its own copy. The book compares this with the Observer pattern: the subject wraps the event in a message, and messaging only makes sure that the notice gets to each observer.1

  shop --- OrderPlaced {order: 41} ---> [ topic: orders ] ---> billing
           a fact, in the past tense                      \--> warehouse
                                                           \-> email

The participants are the producer, the event message, a publish-subscribe channel and the subscribers. The producer does not know the subscribers, and each subscriber decides alone how to react.

A name in the past tense. NServiceBus and MassTransit give the same rule: "Events should be expressed in a noun-verb (past tense) sequence, indicating that something happened."34 OrderPlaced and CustomerAddressUpdated are events. ChargeCard is a Command Message, because it asks for an action.

Attributes that identify the event. CloudEvents is a specification for the attributes of an event. It requires four: id, source, specversion and type. The producer must make source and id together unique for each distinct event, and "Consumers MAY assume that Events with identical source and id are duplicates."5 The type names the kind of event, and it "SHOULD be prefixed with a reverse-DNS name", as in com.example.object.deleted.v2.5

What the event carries. Fowler gives two forms. In event notification, "An event need not carry much data on it, often just some id information and a link back to the sender that can be queried for more information."6 In event-carried state transfer, the event contains the data that changed, so that each receiver keeps its own copy and does not need to call the source.6 The program below sends the same two changes of a customer to three subscribers in the two forms.

import json

# The customer service owns the data, and it publishes an event for each change.
customers = {"c7": {"name": "Ana", "city": "Hanoi"}}
calls_to_source = 0
bytes_sent = 0


def get_customer(cid):
    """The query API of the customer service."""
    global calls_to_source
    calls_to_source += 1
    return dict(customers[cid])


def change_city(cid, city, subscribers, style):
    global bytes_sent
    customers[cid]["city"] = city
    event = {"type": "CustomerAddressUpdated", "id": cid}
    if style == "fat":
        event["data"] = dict(customers[cid])  # the event carries the new state
    for on_event in subscribers:
        bytes_sent += len(json.dumps(event))
        on_event(event)


def make_subscriber(copy):
    def on_event(event):
        # A thin event only says what changed, so the subscriber asks the source.
        data = event.get("data") or get_customer(event["id"])
        copy[event["id"]] = data
    return on_event


for style in ("thin", "fat"):
    calls_to_source, bytes_sent = 0, 0
    copies = [{}, {}, {}]  # billing, shipping and crm keep their own copy
    subscribers = [make_subscriber(c) for c in copies]
    for city in ("Hue", "Da Nang"):
        change_city("c7", city, subscribers, style)
    print(f"{style}: {bytes_sent} bytes of events, {calls_to_source} calls back to the source,"
          f" each copy says {copies[0]['c7']['city']}")
Output
thin: 276 bytes of events, 6 calls back to the source, each copy says Da Nang
fat: 528 bytes of events, 0 calls back to the source, each copy says Da Nang

The thin events are smaller, but each subscriber calls the source for each event: 2 changes and 3 subscribers give 6 calls. The fat events are almost two times as large, and the source gets no calls. Large data has a limit: CloudEvents says that "Intermediaries MUST forward events of a size of 64 KByte or less", and that publishers should keep events compact and link to large data items.5

Timing. The book says that the time of an event is often more important than its content. Many events have no data, and the receiver should act on an event soon. For this reason it says that Guaranteed Delivery often helps little with events, and that a message expiration can make sure that an event is processed soon or not at all.1

No return address. An event does not ask for an answer. Jakarta Messaging says: "Messages sent with a null JMSReplyTo value may be a notification of some event or they may just be some data the sender thinks is of interest."7

Example

Each example file has a topic in memory with two subscribers, billing and email. The shop publishes four event messages with the CloudEvents attributes. The third message is the second one sent again after a network error, with the same id, and both subscribers skip it. Email has no handler for the cancelled event and ignores it: a subscriber reacts only to the events that it cares about, and the producer does not need to know which.

PythonGitHub
import json

# Each event message has the CloudEvents attributes: specversion, id, source and type.
def event(eid, etype, **data):
    return json.dumps({"specversion": "1.0", "id": eid, "source": "/shop",
                       "type": "com.example.order." + etype, "data": data}).encode()


def subscriber(name, handlers):
    seen = set()

    def deliver(raw):
        e = json.loads(raw)
        key = (e["source"], e["id"])
        if key in seen:
            print(f"{name}: skip duplicate {e['id']}")
            return
        seen.add(key)
        handler = handlers.get(e["type"])
        if handler is None:
            print(f"{name}: ignore {e['type']}")
            return
        print(f"{name}: {handler(e['data'])}")
    return deliver


topic = [  # a publish-subscribe channel: each subscriber gets a copy of each event
    subscriber("billing", {
        "com.example.order.placed": lambda d: f"charge order {d['order']}, {d['cents']} cents",
        "com.example.order.cancelled": lambda d: f"refund order {d['order']}"}),
    subscriber("email", {
        "com.example.order.placed": lambda d: f"mail the confirmation of order {d['order']}"}),
]

events = [
    event("e1", "placed", order=41, cents=1999),
    event("e2", "placed", order=42, cents=500),
    event("e2", "placed", order=42, cents=500),  # sent again after a network error
    event("e3", "cancelled", order=41),
]
for raw in events:
    for deliver in topic:
        deliver(raw)
Output
billing: charge order 41, 1999 cents
email: mail the confirmation of order 41
billing: charge order 42, 500 cents
email: mail the confirmation of order 42
billing: skip duplicate e2
email: skip duplicate e2
billing: refund order 41
email: ignore com.example.order.cancelled
  • Verdict: idiom. Python has no publish-subscribe channel in the standard library. A list of subscriber functions is the topic, and json turns each event into bytes and back.
  • Each subscriber keeps a set of (source, id) pairs, so it handles a copy of an event only once.
  • A dict from the type of an event to a function is the set of events that a subscriber cares about. Other types are ignored, not errors.
JavaGitHub
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

public class Main {
    // An event message with the required CloudEvents attributes and the data of the event.
    record CloudEvent(String specversion, String id, String source, String type, Map<String, Integer> data) {}

    record Subscriber(String name, Map<String, Function<Map<String, Integer>, String>> handlers, Set<String> seen) {
        void deliver(CloudEvent e) {
            if (!seen.add(e.source() + " " + e.id())) {
                System.out.println(name + ": skip duplicate " + e.id());
                return;
            }
            var handler = handlers.get(e.type());
            if (handler == null) {
                System.out.println(name + ": ignore " + e.type());
                return;
            }
            System.out.println(name + ": " + handler.apply(e.data()));
        }
    }

    static CloudEvent event(String id, String type, Map<String, Integer> data) {
        return new CloudEvent("1.0", id, "/shop", "com.example.order." + type, data);
    }

    public static void main(String[] args) {
        var billing = new Subscriber("billing", Map.of(
            "com.example.order.placed", d -> "charge order " + d.get("order") + ", " + d.get("cents") + " cents",
            "com.example.order.cancelled", d -> "refund order " + d.get("order")), new HashSet<>());
        var email = new Subscriber("email", Map.of(
            "com.example.order.placed", d -> "mail the confirmation of order " + d.get("order")), new HashSet<>());
        var topic = List.of(billing, email); // each subscriber gets a copy of each event

        var events = List.of(
            event("e1", "placed", Map.of("order", 41, "cents", 1999)),
            event("e2", "placed", Map.of("order", 42, "cents", 500)),
            event("e2", "placed", Map.of("order", 42, "cents", 500)), // sent again after a network error
            event("e3", "cancelled", Map.of("order", 41)));
        for (var e : events) {
            for (var s : topic) {
                s.deliver(e);
            }
        }
    }
}
Output
billing: charge order 41, 1999 cents
email: mail the confirmation of order 41
billing: charge order 42, 500 cents
email: mail the confirmation of order 42
billing: skip duplicate e2
email: skip duplicate e2
billing: refund order 41
email: ignore com.example.order.cancelled
  • Verdict: idiom. Java has no publish-subscribe channel in the standard library and no JSON, so the events here are records in memory. A Jakarta Messaging topic gives the same structure between processes.
  • Set.add returns false when the key is already in the set, so one call both finds and records a duplicate.
  • Map.of gives a map that cannot change, which suits a fixed set of handlers.
using System.Text.Json;

// Each subscriber gets a copy of each event.
var billing = new Subscriber("billing", new()
{
    ["com.example.order.placed"] = d => $"charge order {d["order"]}, {d["cents"]} cents",
    ["com.example.order.cancelled"] = d => $"refund order {d["order"]}",
});
var email = new Subscriber("email", new()
{
    ["com.example.order.placed"] = d => $"mail the confirmation of order {d["order"]}",
});
Subscriber[] topic = [billing, email];

byte[][] events =
[
    Event("e1", "placed", new() { ["order"] = 41, ["cents"] = 1999 }),
    Event("e2", "placed", new() { ["order"] = 42, ["cents"] = 500 }),
    Event("e2", "placed", new() { ["order"] = 42, ["cents"] = 500 }), // sent again after a network error
    Event("e3", "cancelled", new() { ["order"] = 41 }),
];
foreach (var raw in events)
{
    foreach (var s in topic)
    {
        s.Deliver(raw);
    }
}

static byte[] Event(string id, string type, Dictionary<string, int> data) =>
    JsonSerializer.SerializeToUtf8Bytes(new CloudEvent("1.0", id, "/shop", "com.example.order." + type, data));

// An event message with the required CloudEvents attributes and the data of the event.
record CloudEvent(string specversion, string id, string source, string type, Dictionary<string, int> data);

class Subscriber(string name, Dictionary<string, Func<Dictionary<string, int>, string>> handlers)
{
    private readonly HashSet<(string, string)> seen = [];

    public void Deliver(byte[] raw)
    {
        var e = JsonSerializer.Deserialize<CloudEvent>(raw)!;
        if (!seen.Add((e.source, e.id)))
        {
            Console.WriteLine($"{name}: skip duplicate {e.id}");
            return;
        }
        if (!handlers.TryGetValue(e.type, out var handler))
        {
            Console.WriteLine($"{name}: ignore {e.type}");
            return;
        }
        Console.WriteLine($"{name}: {handler(e.data)}");
    }
}
Output
billing: charge order 41, 1999 cents
email: mail the confirmation of order 41
billing: charge order 42, 500 cents
email: mail the confirmation of order 42
billing: skip duplicate e2
email: skip duplicate e2
billing: refund order 41
email: ignore com.example.order.cancelled
  • Verdict: idiom. .NET has no publish-subscribe channel in the base library. An array of subscribers is the topic, and System.Text.Json turns each event into UTF-8 bytes and back.
  • The record CloudEvent has lowercase property names, so the JSON names are the CloudEvents names with no extra options.
  • HashSet.Add with a tuple of the source and the id returns false for a duplicate. Libraries such as MassTransit give Publish over a broker.
package main

import (
	"encoding/json"
	"fmt"
)

// cloudEvent has the required CloudEvents attributes and the data of the event.
type cloudEvent struct {
	SpecVersion string         `json:"specversion"`
	ID          string         `json:"id"`
	Source      string         `json:"source"`
	Type        string         `json:"type"`
	Data        map[string]int `json:"data"`
}

type key struct{ source, id string }

type subscriber struct {
	name     string
	handlers map[string]func(map[string]int) string
	seen     map[key]bool
}

func (s *subscriber) deliver(raw []byte) {
	var e cloudEvent
	if err := json.Unmarshal(raw, &e); err != nil {
		fmt.Printf("%s: invalid message: %v\n", s.name, err)
		return
	}
	k := key{e.Source, e.ID}
	if s.seen[k] {
		fmt.Printf("%s: skip duplicate %s\n", s.name, e.ID)
		return
	}
	s.seen[k] = true
	h, ok := s.handlers[e.Type]
	if !ok {
		fmt.Printf("%s: ignore %s\n", s.name, e.Type)
		return
	}
	fmt.Printf("%s: %s\n", s.name, h(e.Data))
}

func event(id, typ string, data map[string]int) []byte {
	raw, err := json.Marshal(cloudEvent{"1.0", id, "/shop", "com.example.order." + typ, data})
	if err != nil {
		panic(err)
	}
	return raw
}

func main() {
	billing := &subscriber{"billing", map[string]func(map[string]int) string{
		"com.example.order.placed": func(d map[string]int) string {
			return fmt.Sprintf("charge order %d, %d cents", d["order"], d["cents"])
		},
		"com.example.order.cancelled": func(d map[string]int) string {
			return fmt.Sprintf("refund order %d", d["order"])
		},
	}, map[key]bool{}}
	email := &subscriber{"email", map[string]func(map[string]int) string{
		"com.example.order.placed": func(d map[string]int) string {
			return fmt.Sprintf("mail the confirmation of order %d", d["order"])
		},
	}, map[key]bool{}}
	topic := []*subscriber{billing, email} // each subscriber gets a copy of each event

	events := [][]byte{
		event("e1", "placed", map[string]int{"order": 41, "cents": 1999}),
		event("e2", "placed", map[string]int{"order": 42, "cents": 500}),
		event("e2", "placed", map[string]int{"order": 42, "cents": 500}), // sent again after a network error
		event("e3", "cancelled", map[string]int{"order": 41}),
	}
	for _, raw := range events {
		for _, s := range topic {
			s.deliver(raw)
		}
	}
}
Output
billing: charge order 41, 1999 cents
email: mail the confirmation of order 41
billing: charge order 42, 500 cents
email: mail the confirmation of order 42
billing: skip duplicate e2
email: skip duplicate e2
billing: refund order 41
email: ignore com.example.order.cancelled
  • Verdict: idiom. Go has no publish-subscribe channel in the standard library. A slice of subscribers is the topic, and encoding/json encodes the CloudEvents attributes from the struct tags.
  • The struct key with the source and the id is the key of the seen map, because Go can compare structs of strings.
  • A Go channel delivers each value to one receiver only. A topic with channels needs one channel for each subscriber and a loop that copies each event to all of them.

Consequences

Benefits.

  • Loose coupling. The producer does not know the subscribers. A new subscriber starts to read the topic, and the producer does not change.
  • Each subscriber at its own speed. Each subscriber has its own copy, so a slow subscriber does not stop the others.
  • One fact, many uses. Billing, shipping and reports read the same event, and each keeps the data that it needs.

Liabilities.

  • The flow is hard to see. Fowler warns about a flow that runs over many events: "The problem is that it can be hard to see such a flow as it's not explicit in any program text."6
  • Commands in disguise. "A simple example of this trap is when an event is used as a passive-aggressive command."6 If the producer needs one program to act, it should send a command.
  • Duplicates. With at-least-once delivery, the same event can arrive two times. The subscriber must find the copy by its id, as in the examples.
  • A contract with unknown readers. The producer does not know who reads its events, so a change to the data can break a subscriber that the producer has not heard of. A version in the type, as in the CloudEvents example com.example.object.deleted.v2,5 lets the old and new forms live side by side.
  • Thin or fat, both cost. Thin events put load on the source. Fat events make large messages and many copies of the data.

When not to use it

When one program must do a specific action. Send a Command Message to the owner of the action, on a point-to-point channel.

When the sender needs an answer. Use Request-Reply.

Inside one program. A list of callbacks, as in the Observer pattern, is simpler than a channel when all the observers are in the same process and nothing must survive a crash.

Command Message and Document Message. The book gives three kinds of message intent: a command asks the receiver to run a function, a document carries data, and an event tells the receiver about a change in the sender and does not say how to react.8

Event notification and event-carried state transfer. The thin and fat forms above.6

Event sourcing. Fowler: "The core idea of event sourcing is that whenever we make a change to the state of a system, we record that state change as an event".6 The events are then the record of the state, not only notices.

Message Bus. Events are one part of the common set of messages of a Message Bus.

Known uses

  • CloudEvents: the Event type in sdk-go at v2.16.2 holds the context attributes and the data; its comment calls it "the canonical representation of a CloudEvent."9
  • NServiceBus: an event is "Used to communicate that an action has been performed". It "Should be published by the logical owner" and "Cannot be sent".3
  • MassTransit: events are published with Publish, and they have names in the past tense.4

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Event Message (problem and solution under CC BY), problem and solution statements; pattern text
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 5, Message Construction, Event Message
  3. Particular Software, NServiceBus documentation, Messages, events, and commands, Events; Commands vs Events
  4. MassTransit documentation, Messages, Events
  5. CloudEvents, Version 1.0.2, specification, Event; REQUIRED Attributes, id and type; Size Limits
  6. Martin Fowler, What do you mean by Event-Driven?, 2017, Event Notification; Event-Carried State Transfer; Event-Sourcing
  7. Jakarta Messaging 3.1 specification, 3.4.6 JMSReplyTo
  8. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Message Construction, Message intent
  9. CloudEvents SDK for Go v2.16.2 source, event.go, type Event, lines 14 to 23

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/T9VZTP/text.yaml