Microservices patterns
Service boundaries, discovery, inter-service calls, and decomposition patterns.
Event Sourcing Store in Python: Append-Only Log Mock
Mock an append-only event store in Python — record events, list them, and fetch by ID using a simple list-backed class.
class EventStore:
def __init__(self):
self._events = []
def append(self, event):
event_id = len(self._events) + 1
stored_event = {"id": event_id, "data": event}
self._events.append(stored_event)
return stored_event
def get_events(self):
return list(self._ev…
How to Deduplicate Events in Python with SHA256 Hashing
Build an event deduplicator that identifies duplicate inbox messages using SHA256 hashes and tracks duplicate counts per event type.
```python
import hashlib
import json
from collections import defaultdict
class EventDeduplicator:
def __init__(self):
self.seen_hashes = set()
self.duplicate_counts = defaultdict(int)
def process_event(self, event):
event_key = f"{event['event_id']}:{event['timestamp']}"
even…
How to Implement an Outbox Pattern Mock in Python
This code demonstrates a simple in-memory outbox pattern mock for publishing domain events and tracking pending events until they are marked as published.
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4
@dataclass
class DomainEvent:
event_id: str = field(default_factory=lambda: str(uuid4()))
occurred_at: datetime = field(default_factory=datetime.utcnow)
class Outbox:
def __init__(self):
self._events =…
How to Mock Eventual Consistency UI Notes in Python
Simulates a UI note that shows local state until a pending server update is confirmed, mocking eventual consistency behavior in distributed systems.
class EventualConsistencyNote:
def __init__(self, entity_id, note):
self.entity_id = entity_id
self.note = note
self.confirmed = False
self.pending_updates = []
def add_pending_update(self, update):
self.pending_updates.append(update)
def confirm_update(self):
…
How to Mock a Choreography Saga in Python
Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum
class SagaStatus(Enum):
PENDING = "PENDING"
COMPLETING = "COMPLETING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
@dataclass
class EventEnvelope:
event_type: str
order_id: str
sta…
How to Order Partition Key Events in Python (Mock Stream)
Generate a mock event stream grouped by partition key and sort it deterministically by key then sequence in Python.
import itertools
import random
def partition_key_events(keys, events_per_key=3, seed=None):
"""Produce a realistic-looking, but mock, event stream grouped by partition key.
Args:
keys: iterable of partition keys (e.g. strings or ints).
events_per_key: how many events we want per key.
…
Idempotent Consumer Event Processing in Python
Track processed event IDs to skip duplicates and count event types for a reliable, idempotent consumer.
import json
from collections import defaultdict
class EventProcessor:
def __init__(self):
self.processed_ids = set()
self.counts = defaultdict(int)
def process_event(self, event):
event_id = event["id"]
if event_id in self.processed_ids:
return {"status": "skipped"…
Browse by section
Each section groups closely related Python snippets.
Microservices patterns — Python code examples
What you will find here
This page collects microservices patterns snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.