›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

The Pattern Map

Cloud Messaging Patterns and the GoF Patterns Inside Them

October 29, 2026 · 15 min read

Design Patterns, Cloud, Messaging, C#, Python, Azure, Distributed Systems

This post is part of The Pattern Map, my series tracing design patterns from the Gang of Four, through the cloud, to the AI era. Last week's post was about surviving one call that might fail. This one is about what happens when you stop making the call directly and put a message on a queue instead.

Messaging is where the GoF patterns are easiest to spot once you know to look. A message on a queue is a Command: a request turned into an object you can store, pass around and execute later. Publish/subscribe is Observer with a broker in the middle. A saga orchestrator is a Mediator. What's new is that the "object" now travels over a network, so it can arrive late, arrive twice, or not arrive at all.

Cloud patternGoF ancestorWhat it adds
Competing consumersCommand (executed by whichever worker is free)Horizontal scale, at-least-once delivery
Queue-based load levelingCommand (queued requests)A buffer between a bursty producer and a steady consumer
Transactional outboxObserver, made durable (no clean GoF match)The event and the state change commit together
Claim checkProxyA small ticket stands in for a large payload
SagaMediator (orchestration) or Observer (choreography), with Command's undoA business transaction across services, without a distributed lock

I wrote a five-part series on event sourcing and sagas in 2025, so sagas get a map and links here, not a re-explanation.

The rule that shapes everything: at-least-once

Most brokers (Azure Service Bus in peek-lock mode, SQS, RabbitMQ with acks) deliver at least once. If a consumer finishes the work but crashes before it acknowledges the message, the broker hands that message to someone else. That's the right trade-off. Losing a message is worse than seeing it twice.

The consequence: every consumer must be idempotent. I covered idempotency keys for HTTP in the resilience post. For messages, the key is the message ID. Keep that in mind; every pattern below leans on it.

Competing consumers

Several identical workers read from the same queue. Each message goes to exactly one of them. Need more throughput? Add workers. One worker dies? The others keep going, and its unacknowledged messages come back.

In GoF terms, each message is a Command, and the workers are interchangeable invokers. It's worth contrasting with Observer: in pub/sub, every subscriber gets every event. Here, every message gets one handler. Same broker, opposite intent.

Python, with asyncio.Queue standing in for the broker:

import asyncio
import random

processed_ids: set[str] = set()   # in production: a table with a unique constraint on message_id


async def handle(msg: dict) -> str:
    if msg["id"] in processed_ids:          # at-least-once delivery means duplicates WILL arrive
        return "duplicate, skipped"
    processed_ids.add(msg["id"])            # claim it before any await, so two workers can't both pass
    await asyncio.sleep(random.uniform(0.05, 0.15))  # resize a photo, send an email...
    return "done"


async def worker(name: str, queue: asyncio.Queue):
    while True:
        msg = await queue.get()
        outcome = await handle(msg)
        print(f"{name} took {msg['id']}: {outcome} (queue depth {queue.qsize()})")
        queue.task_done()


async def main():
    queue: asyncio.Queue = asyncio.Queue(maxsize=100)  # the buffer that levels the load

    # A burst: 8 messages arrive at once, plus one redelivery of msg-3.
    for i in range(8):
        queue.put_nowait({"id": f"msg-{i}"})
    queue.put_nowait({"id": "msg-3"})

    # Three identical consumers compete for the same queue; each message goes to exactly one.
    workers = [asyncio.create_task(worker(f"worker-{n}", queue)) for n in range(3)]
    await queue.join()
    for w in workers:
        w.cancel()
    print("unique messages processed:", len(processed_ids))


random.seed(7)
asyncio.run(main())
worker-1 took msg-1: done (queue depth 6)
worker-0 took msg-0: done (queue depth 5)
worker-2 took msg-2: done (queue depth 4)
worker-1 took msg-3: done (queue depth 3)
worker-1 took msg-6: done (queue depth 2)
worker-0 took msg-4: done (queue depth 1)
worker-0 took msg-3: duplicate, skipped (queue depth 0)
worker-2 took msg-5: done (queue depth 0)
worker-1 took msg-7: done (queue depth 0)
unique messages processed: 8

Note the order: messages aren't processed in the order they were sent. Competing consumers trade ordering for throughput. If order matters (all events for one order, say), you need partitioning or sessions so related messages go to the same consumer.

The C# version uses System.Threading.Channels, which ships with .NET:

// Bounded: when the buffer is full, producers wait instead of the backend falling over.
var queue = Channel.CreateBounded<OrderMessage>(new BoundedChannelOptions(capacity: 100)
{
    FullMode = BoundedChannelFullMode.Wait
});
var processed = new ConcurrentDictionary<string, bool>();

async Task Consumer(string name)
{
    await foreach (var msg in queue.Reader.ReadAllAsync())
    {
        if (!processed.TryAdd(msg.MessageId, true))   // atomic claim: duplicates are expected
        {
            Console.WriteLine($"{name}: {msg.MessageId} duplicate, skipped");
            continue;
        }
        await Task.Delay(Random.Shared.Next(50, 150));  // the slow part
        Console.WriteLine($"{name}: {msg.MessageId} done");
    }
}

var consumers = Enumerable.Range(0, 3).Select(n => Consumer($"worker-{n}")).ToArray();

// A burst of 8 orders, plus a redelivery of msg-3.
foreach (var id in Enumerable.Range(0, 8).Select(i => $"msg-{i}").Append("msg-3"))
    await queue.Writer.WriteAsync(new OrderMessage(id, 1999));
queue.Writer.Complete();
await Task.WhenAll(consumers);

record OrderMessage(string MessageId, int TotalCents);

Both versions mark the message as claimed before doing the work. Checking after would leave a window where two workers both see "not processed yet" and both do it. In production that claim is an insert into a table with a unique key on the message ID, ideally in the same transaction as the work.

Queue-based load leveling

This is the same code, read for a different reason. Look at the queue depth in the output above: a burst of nine messages arrived at once, and the queue absorbed it while three workers drained it at their own pace.

That's the pattern. Put a queue between a producer that spikes and a consumer that can only go so fast, and the consumer sees a steady flow instead of the spike. The GoF Command pattern already listed "queue or log requests" as one of its uses. The cloud version just makes the queue durable and puts it in a different process.

Two things to get right:

  • Bound the queue. An unbounded queue hides the problem until memory runs out. The C# channel above is bounded with FullMode = Wait, so producers slow down when it's full. That's backpressure.
  • Watch the depth. Queue depth is the best single metric for "are we keeping up?" It's also what autoscalers (KEDA, Azure Functions' scale controller) use to decide when to add consumers.

The trade-off is latency. Leveling means some work happens later. That's fine for "resize this photo" and wrong for "show me my balance."

Transactional outbox

The problem: you need to save an order and publish OrderPlaced. Those are two different systems, a database and a broker, and there's no transaction that spans both. Save then publish, and a crash in between loses the event. Publish then save, and a crash leaves an event for an order that doesn't exist.

The outbox fixes it by not publishing in the request at all. You write the event to an outbox table in the same local transaction as the order. A separate relay reads the outbox and publishes. If the transaction commits, the event will eventually go out. If it rolls back, neither exists.

I described this briefly in Part 3 and Part 5 of the event sourcing series. What I didn't show there is the failure mode of the relay itself, so here it is, runnable, with SQLite from Python's standard library:

import json
import sqlite3
import uuid

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders (id TEXT PRIMARY KEY, total_cents INTEGER NOT NULL);
CREATE TABLE outbox (
    id           TEXT PRIMARY KEY,
    type         TEXT NOT NULL,
    payload      TEXT NOT NULL,
    published_at TEXT            -- NULL until the relay has sent it
);
""")


def place_order(total_cents: int) -> str:
    order_id = str(uuid.uuid4())
    with db:  # ONE local transaction: both rows commit, or neither does
        db.execute("INSERT INTO orders VALUES (?, ?)", (order_id, total_cents))
        db.execute(
            "INSERT INTO outbox (id, type, payload) VALUES (?, ?, ?)",
            (str(uuid.uuid4()), "OrderPlaced", json.dumps({"order_id": order_id, "total": total_cents})),
        )
    return order_id


broker: list[dict] = []  # stand-in for Service Bus / SQS / Kafka


def relay_once(crash_before_marking: bool = False) -> None:
    rows = db.execute(
        "SELECT id, type, payload FROM outbox WHERE published_at IS NULL ORDER BY rowid"
    ).fetchall()
    for msg_id, msg_type, payload in rows:
        broker.append({"message_id": msg_id, "type": msg_type, "body": json.loads(payload)})
        if crash_before_marking:
            print("relay crashed after publishing, before marking")
            return
        with db:
            db.execute("UPDATE outbox SET published_at = datetime('now') WHERE id = ?", (msg_id,))


place_order(4999)
relay_once(crash_before_marking=True)  # message sent, row still unmarked
relay_once()                           # relay restarts and sends it again

ids = [m["message_id"] for m in broker]
print(f"published {len(ids)} times, {len(set(ids))} unique message -> consumers must dedupe on message_id")
relay crashed after publishing, before marking
published 2 times, 1 unique message -> consumers must dedupe on message_id

That's the honest summary of the outbox: it turns "might lose the event" into "might send the event twice." That's a much better problem, because duplicates are what idempotent consumers already handle. Using the outbox row's ID as the broker message ID helps twice: consumers can dedupe on it, and Azure Service Bus's duplicate detection can drop the re-send at the broker if it arrives within the configured window (10 minutes by default, per the docs).

The C# version with Microsoft.Data.Sqlite has the same shape. The important part is the transaction:

string PlaceOrder(int totalCents)
{
    var orderId = Guid.NewGuid().ToString();
    using var tx = db.BeginTransaction();   // one local transaction, no broker involved
    Exec(db, tx, "INSERT INTO orders VALUES ($id, $total)", ("$id", orderId), ("$total", totalCents));
    Exec(db, tx, "INSERT INTO outbox (id, type, payload) VALUES ($id, 'OrderPlaced', $payload)",
        ("$id", Guid.NewGuid().ToString()),
        ("$payload", JsonSerializer.Serialize(new { orderId, totalCents })));
    tx.Commit();
    return orderId;
}

static void Exec(SqliteConnection db, SqliteTransaction? tx, string sql, params (string Name, object Value)[] args)
{
    using var cmd = db.CreateCommand();
    cmd.Transaction = tx;
    cmd.CommandText = sql;
    foreach (var (name, value) in args) cmd.Parameters.AddWithValue(name, value);
    cmd.ExecuteNonQuery();
}

Running the same crash-then-restart sequence prints published 2 times, 1 unique.

Why no clean GoF ancestor? Observer assumes notifying is free and instant. The outbox exists because it isn't. The closest idea is "make the notification part of the state," which is also the core move of event sourcing, where the events are the state.

Claim check

Brokers have size limits. Azure Service Bus Standard caps a message at 256 KB; Premium allows up to 100 MB over AMQP. Even where large messages are allowed, pushing them through the broker is slow and expensive.

Claim check is the coat-check counter. Put the heavy payload in blob storage, send a message with a reference to it (the ticket), and let the consumer fetch the payload when it needs it.

The GoF ancestor is Proxy, specifically the virtual proxy: a lightweight stand-in for an expensive object, loaded on demand.

import hashlib
import json


class BlobStore:
    """Stand-in for Azure Blob Storage / S3."""

    def __init__(self):
        self._blobs: dict[str, bytes] = {}

    def put(self, data: bytes) -> str:
        key = "uploads/" + hashlib.sha256(data).hexdigest()
        self._blobs[key] = data
        return key

    def get(self, key: str) -> bytes:
        return self._blobs[key]


MAX_MESSAGE_BYTES = 256 * 1024  # a typical broker limit; check yours
store = BlobStore()


def send_photo_uploaded(user_id: str, photo: bytes) -> str:
    claim = store.put(photo)  # 1. the heavy payload goes to storage
    message = {"type": "PhotoUploaded", "user_id": user_id,
               "claim_check": claim, "size": len(photo)}  # 2. the message carries a ticket
    body = json.dumps(message)
    assert len(body) < MAX_MESSAGE_BYTES
    return body


def handle_photo_uploaded(body: str) -> None:
    message = json.loads(body)
    photo = store.get(message["claim_check"])  # 3. the consumer redeems the ticket
    print(f"consumer got {len(photo):,} bytes via a {len(body)}-byte message")


raw_photo = b"\x00" * 33_000_000  # a 33 MB camera raw file
handle_photo_uploaded(send_photo_uploaded("bobby", raw_photo))
consumer got 33,000,000 bytes via a 154-byte message

In C# it's the same three steps, with a record as the message:

var blobs = new Dictionary<string, byte[]>();
var photo = new byte[33_000_000];
var claim = $"uploads/{Guid.NewGuid()}";
blobs[claim] = photo;                                         // heavy payload to storage
var body = JsonSerializer.Serialize(new PhotoUploaded("bobby", claim, photo.Length)); // ticket on the bus
var received = JsonSerializer.Deserialize<PhotoUploaded>(body)!;
Console.WriteLine($"consumer got {blobs[received.ClaimCheck].Length:N0} bytes via a {body.Length}-byte message");

record PhotoUploaded(string UserId, string ClaimCheck, int SizeBytes);

Two things the toy version skips. First, who cleans up the blob? Decide whether the consumer deletes it or a lifecycle policy expires it. Second, the ticket is now a pointer to data, so the consumer needs permission to read it. That's where the valet key pattern comes in, which is in the next post.

For app developers this pattern shows up from the other side: the app uploads the photo straight to storage and then tells the API "it's at this path." That's a claim check where the client is the producer.

Saga: Mediator, Observer and Command's undo

A saga is a business transaction that spans services: reserve inventory, charge the card, book shipping. There's no distributed transaction, so each step commits locally, and if a later step fails, earlier steps are undone by compensating actions.

My saga post covers choreography vs orchestration and how to design compensations, and Part 4 builds an orchestrator with Azure Durable Functions. So here's only the map:

  • Orchestration is Mediator. One coordinator tells each service what to do next. Services don't know about each other, just as GoF colleagues talk only to the mediator.
  • Choreography is Observer. Each service reacts to events from the others. No coordinator, but the overall flow lives only in your head (and your tracing).
  • Compensation is Command's undo. GoF Commands can carry an Undo(). A saga step is a command whose undo is a business action, like a refund, not a rollback.

Here's an in-memory orchestrator that shows all three at once. Each step is a Command with a compensating undo, the orchestrator is the Mediator, and when a step fails it runs the undos in reverse order. In production the steps would be messages and the orchestrator's progress would be persisted (that's what Durable Functions does for you), but the shape is the same.

C#

var saga = new SagaOrchestrator(
[
    new("reserve inventory",
        o => Log($"reserved {o.Qty} x {o.Sku}"),
        o => Log($"released {o.Qty} x {o.Sku}")),
    new("charge card",
        o => Log($"charged ${o.Total:F2}"),
        o => Log($"refunded ${o.Total:F2}")),
    new("book shipping",
        o => o.Country is "CA" or "US"
            ? Log($"shipping booked for order {o.Id}")
            : throw new InvalidOperationException($"no carrier for {o.Country}"),
        o => Log($"cancelled shipment for order {o.Id}")),
]);

foreach (var order in new Order[] { new(1, "LENS-35", 1, 499m, "CA"), new(2, "TRIPOD", 2, 180m, "NZ") })
{
    Console.WriteLine($"order {order.Id}:");
    Console.WriteLine($"  -> {await saga.ExecuteAsync(order)}");
}

static Task Log(string message)
{
    Console.WriteLine($"  {message}");
    return Task.CompletedTask;
}

record Order(int Id, string Sku, int Qty, decimal Total, string Country);

// The Command, and its undo: a business action, not a rollback.
record SagaStep(string Name, Func<Order, Task> Run, Func<Order, Task> Compensate);

// The Mediator: steps never call each other.
class SagaOrchestrator(IReadOnlyList<SagaStep> steps)
{
    public async Task<string> ExecuteAsync(Order order)
    {
        var completed = new Stack<SagaStep>();
        foreach (var step in steps)
        {
            try
            {
                await step.Run(order);
                completed.Push(step);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  {step.Name} failed: {ex.Message}");
                while (completed.TryPop(out var done))   // undo in reverse order
                    await done.Compensate(order);
                return "compensated";
            }
        }
        return "completed";
    }
}

Python

from dataclasses import dataclass
from typing import Callable


@dataclass
class SagaStep:
    name: str
    run: Callable[[dict], None]         # the Command
    compensate: Callable[[dict], None]  # its undo: a business action, not a rollback


class SagaOrchestrator:  # the Mediator: steps never call each other
    def __init__(self, steps: list[SagaStep]):
        self.steps = steps

    def execute(self, order: dict) -> str:
        completed: list[SagaStep] = []
        for step in self.steps:
            try:
                step.run(order)
                completed.append(step)
            except Exception as error:
                print(f"  {step.name} failed: {error}")
                for done in reversed(completed):  # undo in reverse order
                    done.compensate(order)
                return "compensated"
        return "completed"


def book_shipping(order: dict) -> None:
    if order["country"] not in {"CA", "US"}:
        raise ValueError(f"no carrier for {order['country']}")
    print(f"  shipping booked for order {order['id']}")


saga = SagaOrchestrator([
    SagaStep("reserve inventory",
             lambda o: print(f"  reserved {o['qty']} x {o['sku']}"),
             lambda o: print(f"  released {o['qty']} x {o['sku']}")),
    SagaStep("charge card",
             lambda o: print(f"  charged ${o['total']:.2f}"),
             lambda o: print(f"  refunded ${o['total']:.2f}")),
    SagaStep("book shipping", book_shipping,
             lambda o: print(f"  cancelled shipment for order {o['id']}")),
])

for order in [
    {"id": 1, "sku": "LENS-35", "qty": 1, "total": 499.0, "country": "CA"},
    {"id": 2, "sku": "TRIPOD", "qty": 2, "total": 180.0, "country": "NZ"},
]:
    print(f"order {order['id']}:")
    print(f"  -> {saga.execute(order)}")

Both print the same thing:

order 1:
  reserved 1 x LENS-35
  charged $499.00
  shipping booked for order 1
  -> completed
order 2:
  reserved 2 x TRIPOD
  charged $180.00
  book shipping failed: no carrier for NZ
  refunded $180.00
  released 2 x TRIPOD
  -> compensated

Notice that order 2's card was charged and then refunded. A saga doesn't prevent the intermediate state; it promises to clean it up. That's why compensations must be idempotent, and why customers sometimes see a pending charge disappear.

And every pattern above shows up inside a saga: steps are messages to competing consumers, each step publishes its result through an outbox, and every handler is idempotent because compensations can run twice too.

Further reading

  • Azure Architecture Center, cloud design patterns catalog
  • Azure Architecture Center, Competing Consumers pattern
  • Azure Architecture Center, Queue-Based Load Leveling pattern
  • Azure Architecture Center, Transactional Outbox pattern with Azure Cosmos DB
  • Azure Architecture Center, Claim-Check pattern
  • Azure Architecture Center, Saga pattern and Compensating Transaction pattern
  • Microsoft Learn, Azure Service Bus duplicate message detection
  • Microsoft Learn, Azure Service Bus quotas and limits (message size by tier)
  • Chris Richardson, microservices.io, Transactional outbox
  • My 2025 series: Part 1, the honest truth about event sourcing · Part 2, Azure building blocks · Part 3, saga orchestration · Part 4, sagas with Durable Functions · Part 5, key concepts
← Previous

Why One Zone's Power Cut Reached a Whole Region: Google's Report

Next →

Blazor Learning Path, Part 1: The Fundamentals

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.