Logo vun Microservice Design Patterns

Microservice Design Patterns

Communautéit
j4flmao
microservice-design-patterns

Use this skill when the user says 'saga pattern', 'distributed transaction', 'compensating transaction', 'choreography vs orchestration', 'CQRS with event sourcing', 'cross-service consistency', 'two-phase commit microservices'. Explains and designs the data-consistency patterns used between microservices (Saga, CQRS, Event Sourcing, Outbox) and how they combine, with a concrete orchestrated saga. Do NOT use for: service decomposition and deployment topology (microservices), CQRS implementation details (backend-cqrs-patterns), event store internals (backend-event-sourcing), outbox implementation (backend-transactional-outbox).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummmicroservice-design-patterns
Stären
41
Forks
6
Matgeliwwert Fichieren
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Microservice Design Patterns an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns/microservices
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/design-patterns/microservices .claude/skills/microservice-design-patterns
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Microservice Design Patterns an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Microservice Design Patterns automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Microservice Design Patterns net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Microservice Data-Consistency Patterns

Purpose

With a database per service, one business operation spans several local transactions. This skill picks the pattern that keeps such operations consistent (sagas with compensation), separates read and write models when needed (CQRS), and shows how event sourcing and the outbox fit in.

Agent Protocol

Trigger

Exact user phrases: "saga pattern", "distributed transaction", "compensating transaction", "choreography vs orchestration", "CQRS with event sourcing", "cross-service consistency", "two-phase commit microservices".

Input Context

  • Business flow and participating services with their data stores.
  • Which steps are reversible, and which have external side effects (payments, emails).
  • Existing messaging infrastructure and workflow engines (Temporal, Camunda, AWS Step Functions).

Output Artifact

Saga step table with compensations, chosen coordination style, and the event/command contracts. No files unless requested.

Response Format

Saga: {name}   Style: {orchestration | choreography}
| # | Service | Action | Compensation | Retryable |
Pivot step: {step after which saga only moves forward}
Isolation countermeasure: {semantic lock | commutative update | reread}
Read model: {CQRS projection or none}

1. Saga: Distributed Transactions Without 2PC

Two-phase commit (XA) needs every participant to support it and holds locks while a coordinator decides; most brokers, NoSQL stores and SaaS APIs cannot participate, and a coordinator failure blocks participants. Sagas replace one global transaction with a sequence of local transactions, each publishing an event or replying to a command. On failure, already-completed steps are undone by compensating transactions (semantic undo such as "refund", not a rollback).

Step types:

  • Compensatable: can be undone (reserve inventory -> release).
  • Pivot: the go/no-go point (charge card). After it, the saga must complete.
  • Retryable: steps after the pivot that must eventually succeed (send confirmation) and are retried until they do.

Order steps so that hard-to-undo actions come as late as possible.

Choreography vs Orchestration

ChoreographyOrchestration
ControlEach service reacts to others' eventsCentral orchestrator sends commands, tracks state
CouplingServices know event types of othersServices know only their own commands
VisibilityFlow is implicit; hard to traceSaga state is explicit and queryable
Good for2-4 steps, simple linear flowsMany steps, branching, timeouts, human tasks
RiskCyclic dependencies, "event spaghetti"Orchestrator becomes a god service if it holds business logic

Durable workflow engines (Temporal, Camunda 8, AWS Step Functions, Azure Durable Functions) implement orchestration with persisted state, timers and retries, so you do not hand-build a state machine.

Orchestrated Saga Example (TypeScript, persisted state machine)

ts
type Step = 'RESERVE_STOCK' | 'CHARGE' | 'SHIP' | 'DONE' | 'COMPENSATING' | 'FAILED';

interface OrderSaga {
  sagaId: string;
  orderId: string;
  step: Step;
  completed: Array<'RESERVE_STOCK' | 'CHARGE'>;
}

interface Deps {
  save(s: OrderSaga): Promise<void>;                       // persist before each command
  send(cmd: string, payload: object, key: string): Promise<void>; // via outbox
}

export async function onReply(saga: OrderSaga, reply: { ok: boolean }, deps: Deps) {
  if (!reply.ok) return compensate(saga, deps);
  switch (saga.step) {
    case 'RESERVE_STOCK':
      saga.completed.push('RESERVE_STOCK');
      saga.step = 'CHARGE';
      await deps.save(saga);
      return deps.send('ChargePayment', { orderId: saga.orderId }, `${saga.sagaId}:charge`);
    case 'CHARGE': // pivot: from here we only move forward
      saga.completed.push('CHARGE');
      saga.step = 'SHIP';
      await deps.save(saga);
      return deps.send('ScheduleShipment', { orderId: saga.orderId }, `${saga.sagaId}:ship`);
    case 'SHIP':
      saga.step = 'DONE';
      return deps.save(saga);
    default:
      throw new Error(`Unexpected reply for saga ${saga.sagaId} in step ${saga.step}`);
  }
}

async function compensate(saga: OrderSaga, deps: Deps) {
  saga.step = 'COMPENSATING';
  await deps.save(saga);
  for (const done of [...saga.completed].reverse()) {
    if (done === 'CHARGE') await deps.send('RefundPayment', { orderId: saga.orderId }, `${saga.sagaId}:refund`);
    if (done === 'RESERVE_STOCK') await deps.send('ReleaseStock', { orderId: saga.orderId }, `${saga.sagaId}:release`);
  }
  saga.step = 'FAILED';
  await deps.save(saga);
}

The third argument is an idempotency key: participants must deduplicate, because commands and replies are delivered at least once.

Lack of Isolation

Sagas are ACD without I: other transactions see intermediate states. Countermeasures:

  • Semantic lock: mark the record PENDING until the saga ends; other operations check the flag.
  • Commutative updates: design operations so order does not matter (credit/debit deltas).
  • Reread value: verify the record is unchanged before overwriting.
  • Version file / pessimistic view: reorder steps to reduce exposure of risky intermediate states.

2. CQRS

Separate the write model (enforces invariants, normalized) from one or more read models (denormalized for specific queries). Read models are updated from events, so they are eventually consistent.

Use when read and write shapes differ heavily, read volume dwarfs writes, or queries span several services' data. Avoid for plain CRUD: it doubles the moving parts. Handle read-your-own-writes by returning the new state from the command, or by waiting for the projection to reach the command's version.

3. Event Sourcing

Persist the sequence of domain events as the source of truth; current state is a left fold over the events. Benefits: complete history, temporal queries, natural event publication. Costs: event schema versioning (upcasters), snapshotting for long streams, and GDPR erasure needs crypto-shredding or stream rewriting, so "never deleted" is a design choice, not a free property.

Event sourcing does not require CQRS in principle, but in practice querying requires projections, so the two are almost always combined.

4. How They Combine

Publishing must be atomic with the state change: use the transactional outbox or CDC, never "commit then publish" in application code.

Decision Table

NeedPattern
Multi-service business transactionSaga (orchestrated if >3 steps)
Atomic "save + publish"Transactional outbox / CDC
Read-heavy cross-service queriesCQRS projection or API composition
Full audit history / temporal queriesEvent sourcing
Strong consistency across two aggregatesReconsider boundaries: maybe they belong in one service

Anti-Patterns

  • Sagas without idempotent participants: redelivery double-charges.
  • Compensations that can fail permanently with no alert or manual-repair queue.
  • Using event sourcing for every service "for consistency".
  • Synchronous HTTP chains (A calls B calls C) pretending to be a transaction.

Checklist

  • Each saga step lists action, compensation, and retry policy; pivot identified.
  • Saga state persisted; timeouts defined for each step.
  • All participants idempotent; messages published via outbox.
  • Isolation countermeasure chosen for each exposed intermediate state.
  • Read models have lag metrics and a rebuild procedure.

References

  • Related skills: skills/backend/universal/microservices/SKILL.md, skills/backend/universal/cqrs-patterns/SKILL.md, skills/backend/universal/event-sourcing/SKILL.md, skills/backend/universal/transactional-outbox/SKILL.md.

Heefeg gestallte Froen

Wat mécht de KI-Skill Microservice Design Patterns?

Use this skill when the user says 'saga pattern', 'distributed transaction', 'compensating transaction', 'choreography vs orchestration', 'CQRS with event sourcing', 'cross-service consistency', 'two-phase commit microservices'. Explains and designs the data-consistency patterns used between microservices (Saga, CQRS, Event Sourcing, Outbox) and how they combine, with a concrete orchestrated saga. Do NOT use for: service decomposition and deployment topology (microservices), CQRS implementation details (backend-cqrs-patterns), event store internals (backend-event-sourcing), outbox implement...

Firwat Microservice Design Patterns op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Microservice Design Patterns besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Microservice Design Patterns an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns/microservices an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Microservice Design Patterns benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Microservice Design Patterns benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Microservice Design Patterns domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Microservice Design Patterns gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇