Microservice Design Patterns logo

Microservice Design Patterns

Community
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).

Overview

Publisherj4flmao
Repositoryagent-skills
Skill namemicroservice-design-patterns
Stars
41
Forks
6
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by j4flmao on GitHub. Read the source before you install it.

Installation

Install the Microservice Design Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns/microservices
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Microservice Design Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Microservice Design Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Microservice Design Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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.

Frequently asked questions

What does the Microservice Design Patterns AI skill do?

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...

Why use Microservice Design Patterns on TypingMind?

Because you install it once and use it with any model. Microservice Design Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Microservice Design Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns/microservices. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Microservice Design Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Microservice Design Patterns?

As many as you like. As long as a model supports skills, you can use Microservice Design Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Microservice Design Patterns AI skill free?

Yes. It is published on GitHub by j4flmao under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇