Microservices patterns
Service boundaries, discovery, inter-service calls, and decomposition patterns.
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 Exactly-Once Deduplication Store in Python
Implement a Python class that deduplicates keys exactly once, tracking first-seen timestamps and duplicate counts.
from datetime import datetime
from typing import Any, Hashable
class ExactlyOnceStore:
def __init__(self) -> None:
self._seen: set[Hashable] = set()
self._first_seen: dict[Hashable, datetime] = {}
self._counts: dict[Hashable, int] = {}
def add(self, key: Hashable, value: Any = None) …
How to mock a SPIFFE workload identity in Python
Generate a mock SPIFFE ID and token for a workload using a trust domain, namespace, and service account.
import hashlib
import json
from dataclasses import dataclass, asdict
@dataclass
class SPIFFEIdentity:
trust_domain: str
namespace: str
service_account: str
@property
def id(self) -> str:
return f"spiffe://{self.trust_domain}/ns/{self.namespace}/sa/{self.service_account}"
def mock_workl…
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"…
Mock a Sidecar Logger with Python Metrics
Simulate a sidecar logger that tracks request counts, error rates, and endpoint hits, producing a metrics snapshot.
import random
import time
from collections import defaultdict
class SidecarLogger:
def __init__(self):
self.metrics = defaultdict(int)
self.total_requests = 0
self.error_count = 0
def log_request(self, endpoint, status_code):
"""Simulate logging a request and updating metrics…
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.