Логотип Microservice Design Patterns

Microservice Design Patterns

Сообщество
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).

Обзор

Издательj4flmao
Репозиторийagent-skills
Название навыкаmicroservice-design-patterns
Звёзды
41
Форки
6
Файлы в комплекте
Только инструкции
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — j4flmao. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Microservice Design Patterns в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns/microservices
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

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
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Microservice Design Patterns в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Microservice Design Patterns, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Microservice Design Patterns не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

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.

Часто задаваемые вопросы

Что делает навык ИИ 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...

Зачем использовать Microservice Design Patterns в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Microservice Design Patterns — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Microservice Design Patterns в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/design-patterns/microservices. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Microservice Design Patterns?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Microservice Design Patterns?

С любым количеством. В TypingMind вы можете использовать Microservice Design Patterns с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Microservice Design Patterns?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — j4flmao. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇