›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 Structure and Migration Patterns and the GoF Patterns Inside Them

November 1, 2026 · 15 min read

Design Patterns, Cloud, Architecture, C#, Python, Swift, Azure

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. It's the last of three cloud posts. Resilience was about surviving a failing call, and messaging was about not making the call directly at all. This one is about where things sit: what goes in front of a service, beside it, or around it while you replace it.

If the GoF structural patterns had a family reunion, it would look like this post. Almost every pattern here is a Proxy, a Decorator or a Facade, moved from an object boundary to a process or network boundary.

Cloud patternGoF ancestorWhat it adds
Cache-asideProxy (caching), but explicitThe app owns the cache logic; the cache can be stale
SidecarDecoratorAdds capabilities to a service in a separate process, in any language
AmbassadorProxy (remote)A local stand-in for a remote service that handles the network for you
Strangler figFacade (+ routing Proxy, + Adapter at the seams)Replace a system one route at a time behind a stable front door
Valet keyProtection Proxy, invertedInstead of proxying the data, hand the client a narrow, expiring key

Cache-aside

The app checks the cache first. On a miss it reads the database, puts the result in the cache, and returns it. On a write it updates the database and invalidates the cache entry.

The GoF ancestor is a caching Proxy: something that sits in front of an expensive object and remembers answers. The difference is in who does the work. A proxy (or a "read-through" cache) hides the caching from the caller. Cache-aside puts it in the application's code, in plain sight. That's more code, but it works with any cache and any database, and you decide exactly what gets cached.

The part I underestimated for years is the cold cache. At the end of September, Azure's post-incident review for an outage in Sweden Central described a deployment that cleared caches during peak hours, with backend traffic rising to about 20 times normal. When a popular key is missing, every request that wants it misses at the same moment and goes to the database together. That's a cache stampede.

Two cheap defenses are built into the version below:

  • Single-flight: if a load for a key is already running, wait for it instead of starting another.
  • Jittered TTLs: add a little randomness to expiry so keys cached together don't all expire together.
import asyncio
import random
import time

db_calls = 0


async def load_product_from_db(product_id: str) -> dict:
    global db_calls
    db_calls += 1
    await asyncio.sleep(0.1)  # the expensive read
    return {"id": product_id, "price": 499}


class CacheAside:
    def __init__(self, loader, ttl_seconds: float):
        self._loader, self._ttl = loader, ttl_seconds
        self._cache: dict[str, tuple[float, dict]] = {}
        self._in_flight: dict[str, asyncio.Future] = {}

    async def get(self, key: str) -> dict:
        hit = self._cache.get(key)
        if hit and hit[0] > time.monotonic():
            return hit[1]                                  # 1. hit: done
        if key in self._in_flight:                         # 2. someone is already loading it:
            return await self._in_flight[key]              #    wait for them (no stampede)
        future = asyncio.get_running_loop().create_future()
        self._in_flight[key] = future
        try:
            value = await self._loader(key)                # 3. miss: read the source of truth
            ttl = self._ttl * random.uniform(0.9, 1.1)     # jittered TTL: keys don't all expire together
            self._cache[key] = (time.monotonic() + ttl, value)   # 4. populate the cache
            future.set_result(value)
            return value
        except Exception as e:
            future.set_exception(e)
            raise
        finally:
            del self._in_flight[key]

    def invalidate(self, key: str) -> None:               # call after a write to the database
        self._cache.pop(key, None)


async def main():
    products = CacheAside(load_product_from_db, ttl_seconds=60)
    # 100 requests for the same cold key arrive at once (think: right after a deploy).
    results = await asyncio.gather(*(products.get("sku-1") for _ in range(100)))
    print(f"{len(results)} requests, {db_calls} database call(s)")
    await products.get("sku-1")
    print(f"warm read, still {db_calls} database call(s)")


asyncio.run(main())
100 requests, 1 database call(s)
warm read, still 1 database call(s)

Without the _in_flight check, that first line says 100 database calls.

In C#, ConcurrentDictionary plus Lazy<Task<T>> gives the same single-flight behavior. It's the same trick as the idempotency handler in the resilience post:

sealed class CacheAside<T>(Func<string, Task<T>> loader, TimeSpan ttl)
{
    private readonly ConcurrentDictionary<string, (DateTimeOffset Expires, T Value)> _cache = new();
    private readonly ConcurrentDictionary<string, Lazy<Task<T>>> _inFlight = new();

    public async Task<T> GetAsync(string key)
    {
        if (_cache.TryGetValue(key, out var hit) && hit.Expires > DateTimeOffset.UtcNow)
            return hit.Value;                                        // hit

        var load = _inFlight.GetOrAdd(key, k => new Lazy<Task<T>>(async () =>
        {
            try
            {
                var value = await loader(k);                         // miss: source of truth
                var jitter = Random.Shared.NextDouble() * 0.2 + 0.9;  // TTL +/- 10%
                _cache[k] = (DateTimeOffset.UtcNow + ttl * jitter, value);
                return value;
            }
            finally { _inFlight.TryRemove(k, out _); }
        }));
        return await load.Value;                                     // concurrent misses share one load
    }

    public void Invalidate(string key) => _cache.TryRemove(key, out _);
}

This prints 100 requests, 1 database call(s) too. In a real .NET app, Microsoft's HybridCache library already does this: its docs say only one concurrent caller per key runs the factory, and the rest wait for the result. Check it before writing your own. These in-process versions also only protect one server. With twenty instances behind a load balancer, a cold distributed cache can still see twenty loads at once, which is far better than thousands.

On writes: update the database, then delete the cache key. Deleting rather than updating means the next reader loads the fresh value, and you avoid two writers racing to put different values in the cache.

Cache-aside is one strategy of several. Caching in Depth, Part 1 compares it with read-through, write-through, write-behind and refresh-ahead, and Part 2 covers every layer you can cache at, from the browser to the database.

Sidecar and ambassador

These two need very little code, because the whole point is that they live outside your code. The code that matters is how small your side gets.

A sidecar is a helper process deployed next to your service, sharing its lifecycle and usually its network namespace: same pod in Kubernetes, same app in Azure Container Apps. It adds things like log shipping, TLS, metrics or configuration reload without touching the service. That's the Decorator pattern at process level: wrap something to add behavior, without changing its interface. And because it's a separate process, it works the same whether the service is written in C#, Python or Go.

An ambassador is a specific kind of sidecar: a local proxy for outbound calls. Your service talks to localhost, and the ambassador handles the messy network part: retries, circuit breaking, TLS, routing, metrics. That's a GoF remote Proxy, a local object standing in for a remote one.

The useful realization for me: an ambassador is the resilience post moved out of process. Service meshes put an Envoy proxy beside every service for exactly this. Dapr runs as a sidecar and gives your app HTTP or gRPC APIs for state, pub/sub and service invocation.

Here's what calling another service looks like through Dapr's sidecar. Your app only knows localhost; per Dapr's docs, the sidecar resolves the orders service, applies mTLS between sidecars, records the trace, and applies whatever resiliency policy you configured.

C#

// The app only knows localhost. The Dapr sidecar (the ambassador) does the rest.
var daprPort = Environment.GetEnvironmentVariable("DAPR_HTTP_PORT") ?? "3500";
using var http = new HttpClient { BaseAddress = new Uri($"http://localhost:{daprPort}") };

var order = await http.GetStringAsync("/v1.0/invoke/orders/method/orders/42");
Console.WriteLine(order);

Python

import os
import urllib.request

# The app only knows localhost. The Dapr sidecar (the ambassador) does the rest.
dapr_port = os.environ.get("DAPR_HTTP_PORT", "3500")
url = f"http://localhost:{dapr_port}/v1.0/invoke/orders/method/orders/42"

with urllib.request.urlopen(url, timeout=5) as response:
    print(response.read().decode())

Compare that with the Polly pipeline in the resilience post: no retry policy, no breaker, no TLS setup in the app. It all moved into the process next door, which is also why the two snippets are nearly identical. The language barely matters any more.

The trade-offs are real: an extra hop on every call, more memory per instance, and one more thing to upgrade and debug. For a single small API, a library like Polly is simpler. The sidecar earns its keep when you have many services in different languages that all need the same behavior.

Strangler fig

Martin Fowler named this after the strangler fig vine, which grows around a host tree until it can stand on its own. You put a front door in front of the legacy system. At first it forwards everything to the old code. Then you move one route at a time to new code, until nothing is left on the old side and you can switch it off.

The GoF ancestors are layered:

  • The front door is a Facade: one stable interface over a messy subsystem, so clients never notice what's behind it changing.
  • Its routing is a Proxy that decides, per request, which real object to forward to.
  • Where the new code has to talk to the old data model, you add an Adapter, which the Azure catalog calls an anti-corruption layer.

A minimal facade in Python, with a percentage rollout per route:

import hashlib
from typing import Callable

Handler = Callable[[str, str], str]


def legacy_app(path: str, user_id: str) -> str:
    return f"legacy handled {path}"


def new_orders_service(path: str, user_id: str) -> str:
    return f"new service handled {path}"


class StranglerFacade:
    """One front door. Routes move from legacy to new one at a time; callers never notice."""

    def __init__(self, legacy: Handler):
        self._legacy = legacy
        self._routes: list[tuple[str, Handler, int]] = []  # (prefix, handler, % of users)

    def migrate(self, prefix: str, handler: Handler, percent: int) -> None:
        self._routes = [r for r in self._routes if r[0] != prefix] + [(prefix, handler, percent)]

    def handle(self, path: str, user_id: str) -> str:
        for prefix, handler, percent in self._routes:
            if path.startswith(prefix) and self._bucket(user_id) < percent:
                return handler(path, user_id)
        return self._legacy(path, user_id)                # everything not yet migrated

    @staticmethod
    def _bucket(user_id: str) -> int:
        # Stable per user: the same person always lands on the same side during a rollout.
        return int(hashlib.sha256(user_id.encode()).hexdigest(), 16) % 100


front_door = StranglerFacade(legacy_app)
front_door.migrate("/orders", new_orders_service, percent=10)

users = [f"user-{i}" for i in range(1000)]
on_new = sum("new service" in front_door.handle("/orders/42", u) for u in users)
print(f"/orders at 10%: {on_new} of 1000 users on the new service")
print(front_door.handle("/invoices/7", "user-1"))

front_door.migrate("/orders", new_orders_service, percent=100)
print(front_door.handle("/orders/42", "user-1"))
/orders at 10%: 95 of 1000 users on the new service
legacy handled /invoices/7
new service handled /orders/42

The C# version is the same idea:

sealed class StranglerFacade(Func<string, string> legacy)
{
    private readonly Dictionary<string, (Func<string, string> Handler, int Percent)> _routes = new();

    public void Migrate(string prefix, Func<string, string> handler, int percent) => _routes[prefix] = (handler, percent);

    public string Handle(string path, string userId)
    {
        foreach (var (prefix, (handler, percent)) in _routes)
            if (path.StartsWith(prefix) && Bucket(userId) < percent)
                return handler(path);
        return legacy(path);
    }

    private static int Bucket(string userId) =>
        (int)(BitConverter.ToUInt32(SHA256.HashData(Encoding.UTF8.GetBytes(userId))) % 100);
}

In practice you wouldn't write this router. It's a reverse proxy (YARP in .NET, an API gateway, Azure Front Door) with routing rules. What matters is the discipline the pattern forces:

  • Hash on something stable (the user ID), not a random number per request, so one person doesn't bounce between old and new behavior.
  • Move small slices and keep the rollback a config change.
  • Watch the data. Routing traffic is the easy half. If old and new code both write to the same tables, you need a plan for who owns which data, and when.
  • Actually finish. A strangler fig that stops at 80% leaves you running two systems forever.

There's a mobile version of this too. An app can't be strangled behind a router, because old app versions live on users' phones for years. The API they call can be, which is one more reason to keep a stable facade in front of your backend from day one.

Valet key

Say your app lets users upload 33 MB photos. The obvious design sends the bytes through your API to storage. Your API now spends its CPU, memory and bandwidth relaying bytes it doesn't even look at.

The valet key flips that. The client asks your API for permission. The API checks who they are, then issues a narrow, short-lived token: write access to one blob path, for five minutes. The client uploads directly to storage. Your API never touches the bytes.

The GoF ancestor is the protection Proxy, which controls access to an object by checking permissions on every call. The valet key keeps the access control but takes the proxy out of the data path. The check happens once, when the key is issued, and the storage service enforces the key's limits.

Here's the mechanism in Python, with an HMAC signature, to show why it's safe. This is a teaching version; real storage services use their own formats:

import hashlib
import hmac
import time
from urllib.parse import parse_qs, urlencode, urlsplit

SECRET = b"server-side-only"  # never leaves the server; in Azure this is the account or user delegation key


def issue_valet_key(blob_path: str, permissions: str, ttl_seconds: int) -> str:
    """The API's only job: decide if this user may do this, then hand back a narrow, short-lived URL."""
    expires = int(time.time()) + ttl_seconds
    to_sign = f"{blob_path}\n{permissions}\n{expires}".encode()
    sig = hmac.new(SECRET, to_sign, hashlib.sha256).hexdigest()
    return f"https://storage.example.com{blob_path}?" + urlencode({"sp": permissions, "se": expires, "sig": sig})


def storage_accepts(url: str, method: str) -> bool:
    """What the storage service checks on every request. Your API isn't involved at all."""
    parts = urlsplit(url)
    q = {k: v[0] for k, v in parse_qs(parts.query).items()}
    to_sign = f"{parts.path}\n{q['sp']}\n{q['se']}".encode()
    expected = hmac.new(SECRET, to_sign, hashlib.sha256).hexdigest()
    needed = {"PUT": "w", "GET": "r"}[method]
    return (hmac.compare_digest(expected, q["sig"])
            and int(q["se"]) > time.time()
            and needed in q["sp"])


url = issue_valet_key("/uploads/user-42/photo.cr3", permissions="w", ttl_seconds=300)
print("upload allowed:", storage_accepts(url, "PUT"))
print("read allowed:", storage_accepts(url, "GET"))           # write-only key
tampered = url.replace("user-42", "user-43")
print("other user's path:", storage_accepts(tampered, "PUT"))
expired = issue_valet_key("/uploads/user-42/photo.cr3", "w", ttl_seconds=-1)
print("expired key:", storage_accepts(expired, "PUT"))
upload allowed: True
read allowed: False
other user's path: False
expired key: False

Change the path, the permissions or the expiry, and the signature no longer matches. That's the whole trick.

In Azure, the real thing is a shared access signature (SAS). With the Azure.Storage.Blobs SDK, a write-only SAS for a single blob looks like this:

// Demo credential so this runs offline. In production prefer a user delegation SAS (Microsoft Entra ID).
var credential = new StorageSharedKeyCredential("myphotoapp", Convert.ToBase64String(new byte[64]));
var sas = new BlobSasBuilder
{
    BlobContainerName = "uploads",
    BlobName = "user-42/photo.cr3",
    Resource = "b",                                   // a single blob, not the container
    StartsOn = DateTimeOffset.UtcNow.AddMinutes(-15), // Microsoft suggests 15+ min back, for clock skew
    ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5),
    Protocol = SasProtocol.Https
};
sas.SetPermissions(BlobSasPermissions.Create | BlobSasPermissions.Write);
var uploadUrl = $"https://myphotoapp.blob.core.windows.net/uploads/user-42/photo.cr3?{sas.ToSasQueryParameters(credential)}";
// permissions: cw, resource: b, has signature: True

The comment matters. Signing with the account key works, but anyone holding that key can mint any SAS they like. Microsoft's guidance is to prefer a user delegation SAS, signed with credentials from Microsoft Entra ID, when you can.

The app side is where this pays off for me as an app developer. The phone gets a URL from my API and uploads straight to storage with URLSession:

import Foundation

struct UploadTicket: Decodable {
    let uploadURL: URL      // the SAS URL your API issued
    let expiresAt: Date
}

func makeUploadRequest(ticket: UploadTicket, fileSize: Int) -> URLRequest {
    var req = URLRequest(url: ticket.uploadURL)
    req.httpMethod = "PUT"
    req.setValue("BlockBlob", forHTTPHeaderField: "x-ms-blob-type")  // required by Azure's Put Blob
    req.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
    req.setValue(String(fileSize), forHTTPHeaderField: "Content-Length")
    return req
}

let json = """
{"uploadURL": "https://myphotoapp.blob.core.windows.net/uploads/user-42/photo.cr3?sp=cw&sr=b&sig=abc",
 "expiresAt": "2026-11-01T14:05:00Z"}
"""
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let ticket = try! decoder.decode(UploadTicket.self, from: Data(json.utf8))
let request = makeUploadRequest(ticket: ticket, fileSize: 33_000_000)
// In the app: try await URLSession.shared.upload(for: request, fromFile: localFileURL)
print(request.httpMethod!, request.url!.host()!, request.value(forHTTPHeaderField: "x-ms-blob-type")!)
// PUT myphotoapp.blob.core.windows.net BlockBlob

After the upload, the app tells the API "it's at uploads/user-42/photo.cr3," which is the claim check from the messaging post, with the client as the producer. The two patterns are made for each other.

Rules I'd follow, most of them straight from Microsoft's SAS best practices: scope each key to one path, grant the fewest permissions (write without read for uploads), keep expiry short, use HTTPS only, and validate what was uploaded before using it. And never let the client choose the path. The server decides where the file goes.

The pattern behind the patterns

Looking back at all three cloud posts, I count more Proxies than anything else: the circuit breaker, the bulkhead, the claim check, the cache, the ambassador, the strangler's router, the valet key's inverted version of it. That makes sense. The network is the place where you most want something standing between you and the thing you're calling.

Next in The Pattern Map is the AI era, where the same question comes back in a new form: what do you put between your app and a model?

Further reading

  • Azure Architecture Center, cloud design patterns catalog
  • Azure Architecture Center, Cache-Aside pattern
  • Azure Architecture Center, Sidecar pattern
  • Azure Architecture Center, Ambassador pattern
  • Azure Architecture Center, Strangler Fig pattern
  • Azure Architecture Center, Anti-Corruption Layer pattern
  • Azure Architecture Center, Valet Key pattern
  • Microsoft Learn, shared access signatures overview (including user delegation SAS)
  • Martin Fowler, StranglerFigApplication
  • Azure status history, post-incident reviews (tracking ID 7QL5-Z50, Sweden Central, Sep 29, 2026)
← Previous

Blazor Learning Path, Part 3: Advanced Blazor

Next →

Blazor Learning Path, Part 2: Building Real Features

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.