Logotipo de Backend Event Driven Architecture

Backend Event Driven Architecture

Comunidad
j4flmao
backend-event-driven-architecture

Use this skill when the user says 'event-driven architecture', 'EDA', 'publish domain events', 'kafka producer', 'kafka consumer', 'rabbitmq exchange', 'event broker', 'at-least-once delivery', 'event ordering', 'consumer group'. Designs broker-based event flows (Kafka or RabbitMQ): event shape, topic/exchange layout, partitioning for ordering, delivery guarantees, consumer idempotency, retries and dead-lettering, with working producer/consumer code. Do NOT use for: event sourcing as a persistence model (backend-event-sourcing), broker operations and tuning (backend-message-queue), reliable publish from a DB transaction (backend-transactional-outbox), stream processing with Flink/Kafka Streams (backend-data-streaming).

Descripción general

Editorj4flmao
Repositorioagent-skills
Nombre de la habilidadbackend-event-driven-architecture
Estrellas
41
Forks
6
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por j4flmao en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Backend Event Driven Architecture en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/event-driven-architecture
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

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/event-driven-architecture .claude/skills/backend-event-driven-architecture
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Backend Event Driven Architecture en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Backend Event Driven Architecture automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Backend Event Driven Architecture no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Event-Driven Architecture

Purpose

Decouple services by having producers publish facts ("OrderPlaced") to a broker and consumers react independently. The skill covers the design decisions that make this reliable in practice: what goes in an event, how ordering and delivery guarantees work, and how consumers stay correct under redelivery.

Agent Protocol

Trigger

Exact user phrases: "event-driven architecture", "EDA", "publish domain events", "kafka producer", "kafka consumer", "rabbitmq exchange", "event broker", "at-least-once delivery", "event ordering", "consumer group".

Input Context

  • Business flow and which services produce/consume.
  • Broker in use or candidates (Kafka, RabbitMQ, cloud: SNS/SQS, Pub/Sub, Event Hubs).
  • Ordering, latency and replay requirements.
  • Language and client library.

Output Artifact

Event catalogue, topology (topics/exchanges, keys, consumer groups), and producer/consumer code. No files unless requested.

Response Format

Event: {PastTenseName} v{n}   Key: {partition key}
Topic/Exchange: {name}         Producers: {svc}   Consumers: {svc,...}
Delivery: at-least-once        Ordering: per {key}
Consumer idempotency: {dedupe table | natural upsert}
Failure: retry {n} with backoff -> DLQ {name}

Core Concepts

ConceptMeaning
Event notificationThin event ("OrderPlaced id=42"); consumers call back for details. Low coupling on schema, higher coupling at runtime
Event-carried state transferEvent carries the data consumers need; no callback; larger payloads, schema is a contract
Command vs eventCommand = request to one handler ("ChargeCard"); event = fact for any number of subscribers ("PaymentCaptured")
Delivery guaranteeBrokers give at-most-once or at-least-once to consumers. "Exactly-once" end to end requires idempotent consumers or transactional read-process-write inside one system (Kafka transactions)

Broker Choice

NeedKafkaRabbitMQ
Replay history / new consumers reading the pastYes (retention-based log)No by default (queues delete on ack); RabbitMQ Streams add a log
Per-key ordering at scaleYes, per partitionPer queue, single active consumer needed for strict order
Flexible routing (topic/headers patterns)Limited (topic per event type)Rich (direct, topic, fanout, headers exchanges)
Per-message TTL, priority, delayed retryNot nativeNative (TTL, priority queues, DLX)
Very high throughput fan-outStrongGood, lower ceiling

Event Design Rules

  1. Name events in past tense for facts that already happened (OrderPlaced, not PlaceOrder).
  2. Include an envelope: event_id (unique, for dedupe), type, version, occurred_at, source, subject/aggregate_id, optional trace_id. CloudEvents is a standard envelope worth adopting.
  3. Choose the partition key = aggregate ID so all events for one entity are ordered.
  4. Evolve schemas backward-compatibly (add optional fields only); use a schema registry (Avro/Protobuf/JSON Schema) for Kafka.
  5. Publish only after the state change is durable. Writing to the DB and the broker in one request without the outbox pattern creates dual-write inconsistencies.

Kafka Producer (Go, confluent-kafka-go v2)

go
package events

import (
	"encoding/json"
	"fmt"

	"github.com/confluentinc/confluent-kafka-go/v2/kafka"
)

type OrderPlaced struct {
	EventID    string `json:"event_id"`
	OrderID    string `json:"order_id"`
	CustomerID string `json:"customer_id"`
	TotalCents int64  `json:"total_cents"`
	OccurredAt string `json:"occurred_at"`
}

func NewProducer(brokers string) (*kafka.Producer, error) {
	return kafka.NewProducer(&kafka.ConfigMap{
		"bootstrap.servers":  brokers,
		"acks":               "all", // wait for in-sync replicas
		"enable.idempotence": true,  // no duplicates from producer retries
		"linger.ms":          5,
	})
}

// PublishOrderPlaced blocks until the broker acknowledges the write.
func PublishOrderPlaced(p *kafka.Producer, topic string, evt OrderPlaced) error {
	payload, err := json.Marshal(evt)
	if err != nil {
		return fmt.Errorf("marshal event %s: %w", evt.EventID, err)
	}
	delivery := make(chan kafka.Event, 1)
	err = p.Produce(&kafka.Message{
		TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny},
		Key:            []byte(evt.OrderID), // per-order ordering
		Value:          payload,
		Headers:        []kafka.Header{{Key: "type", Value: []byte("OrderPlaced.v1")}},
	}, delivery)
	if err != nil {
		return fmt.Errorf("enqueue event %s: %w", evt.EventID, err)
	}
	m := (<-delivery).(*kafka.Message)
	if m.TopicPartition.Error != nil {
		return fmt.Errorf("deliver event %s: %w", evt.EventID, m.TopicPartition.Error)
	}
	return nil
}

Create one producer per process and reuse it; call p.Flush(timeoutMs) and p.Close() on shutdown.

Kafka Consumer With Manual Commit

go
func Consume(brokers, group, topic string, handle func(*kafka.Message) error) error {
	c, err := kafka.NewConsumer(&kafka.ConfigMap{
		"bootstrap.servers":  brokers,
		"group.id":           group,
		"auto.offset.reset":  "earliest",
		"enable.auto.commit": false, // commit only after successful handling
	})
	if err != nil {
		return fmt.Errorf("create consumer for group %s: %w", group, err)
	}
	defer c.Close()
	if err := c.SubscribeTopics([]string{topic}, nil); err != nil {
		return fmt.Errorf("subscribe %s: %w", topic, err)
	}
	for {
		msg, err := c.ReadMessage(-1)
		if err != nil {
			if kerr, ok := err.(kafka.Error); ok && kerr.IsFatal() {
				return fmt.Errorf("fatal consumer error: %w", err)
			}
			continue // transient errors are retried by the client
		}
		if err := handle(msg); err != nil {
			// Hand off to retry/DLQ topic rather than blocking the partition forever.
			return fmt.Errorf("handle offset %v: %w", msg.TopicPartition, err)
		}
		if _, err := c.CommitMessage(msg); err != nil {
			return fmt.Errorf("commit offset %v: %w", msg.TopicPartition, err)
		}
	}
}

Idempotent Consumer

At-least-once means duplicates will arrive (rebalances, crashes before commit). Make the handler safe:

sql
CREATE TABLE processed_events (
  consumer   text        NOT NULL,
  event_id   text        NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (consumer, event_id)
);
-- In the same transaction as the side effect:
INSERT INTO processed_events (consumer, event_id) VALUES ('billing', $1)
ON CONFLICT DO NOTHING;   -- 0 rows affected => duplicate, skip side effect

Retries and Dead-Lettering

  • Kafka: on failure publish to orders.retry.1m, orders.retry.10m, then orders.dlq, committing the original offset. Blocking retries in place stall the whole partition.
  • RabbitMQ: basic.nack with requeue=false routes to the queue's dead-letter exchange (x-dead-letter-exchange); use TTL queues for delayed retry.
  • Classify errors: validation/poison messages go straight to DLQ; transient (timeouts) retry with exponential backoff and jitter.
  • Alert on DLQ depth and provide a replay tool.

Anti-Patterns

Anti-patternFix
Publishing before DB commit, or DB + broker dual writeTransactional outbox or CDC
Random/null keys when order mattersKey by aggregate ID
Auto-commit with slow handlersManual commit after processing
Events that are disguised RPC ("PleaseSendEmail" awaiting reply)Use a command queue or synchronous call
Breaking schema changes on an existing topicVersion the event type; dual-publish during migration
One giant "events" topic for everythingTopic per event type or bounded context

Checklist

  • Event catalogue with owners, schema versions and keys.
  • Producer: acks=all, idempotence on, publish via outbox.
  • Consumers idempotent; offsets committed after processing.
  • Retry topics/queues and DLQ with alerting and replay.
  • Consumer lag, DLQ depth and end-to-end latency monitored.
  • Trace context propagated in message headers.

References

  • Related skills: skills/backend/universal/event-driven/SKILL.md, skills/backend/universal/message-queue/SKILL.md, skills/backend/universal/transactional-outbox/SKILL.md, skills/backend/universal/event-sourcing/SKILL.md.

Preguntas frecuentes

¿Qué hace la habilidad de IA Backend Event Driven Architecture?

Use this skill when the user says 'event-driven architecture', 'EDA', 'publish domain events', 'kafka producer', 'kafka consumer', 'rabbitmq exchange', 'event broker', 'at-least-once delivery', 'event ordering', 'consumer group'. Designs broker-based event flows (Kafka or RabbitMQ): event shape, topic/exchange layout, partitioning for ordering, delivery guarantees, consumer idempotency, retries and dead-lettering, with working producer/consumer code. Do NOT use for: event sourcing as a persistence model (backend-event-sourcing), broker operations and tuning (backend-message-queue), reliable...

¿Por qué usar Backend Event Driven Architecture en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Backend Event Driven Architecture está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Backend Event Driven Architecture en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/j4flmao/agent-skills/tree/main/skills/backend/event-driven-architecture. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Backend Event Driven Architecture?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Backend Event Driven Architecture?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Backend Event Driven Architecture con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Backend Event Driven Architecture?

Sí. j4flmao la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇