event-driven-architect
Designs event-driven architectures with event sourcing, CQRS, pub/sub patterns, and domain events for decoupled systems. Use when users request "event sourcing", "CQRS", "domain events", "pub/sub", or "event-driven".
What this skill does
# Event-Driven Architect
Build decoupled, scalable systems with event-driven patterns.
## Core Workflow
1. **Identify domain events**: Define what happened
2. **Design event schema**: Structure event payloads
3. **Implement event bus**: Publish and subscribe
4. **Add event handlers**: React to events
5. **Consider CQRS**: Separate reads and writes
6. **Enable event sourcing**: Store event history
## Event Fundamentals
### Event Structure
```typescript
// events/base.ts
export interface DomainEvent<T = unknown> {
id: string;
type: string;
aggregateId: string;
aggregateType: string;
payload: T;
metadata: {
timestamp: Date;
version: number;
correlationId?: string;
causationId?: string;
userId?: string;
};
}
// Type-safe event creator
export function createEvent<T>(
type: string,
aggregateType: string,
aggregateId: string,
payload: T,
metadata?: Partial<DomainEvent['metadata']>
): DomainEvent<T> {
return {
id: crypto.randomUUID(),
type,
aggregateType,
aggregateId,
payload,
metadata: {
timestamp: new Date(),
version: 1,
...metadata,
},
};
}
```
### Define Domain Events
```typescript
// events/order.events.ts
export interface OrderCreatedPayload {
customerId: string;
items: Array<{
productId: string;
quantity: number;
price: number;
}>;
totalAmount: number;
shippingAddress: Address;
}
export interface OrderPaidPayload {
paymentId: string;
amount: number;
method: 'card' | 'bank' | 'wallet';
}
export interface OrderShippedPayload {
trackingNumber: string;
carrier: string;
estimatedDelivery: string;
}
export interface OrderCancelledPayload {
reason: string;
cancelledBy: string;
refundAmount?: number;
}
// Event types
export type OrderEvent =
| DomainEvent<OrderCreatedPayload> & { type: 'OrderCreated' }
| DomainEvent<OrderPaidPayload> & { type: 'OrderPaid' }
| DomainEvent<OrderShippedPayload> & { type: 'OrderShipped' }
| DomainEvent<OrderCancelledPayload> & { type: 'OrderCancelled' };
// Event creators
export const OrderEvents = {
created: (orderId: string, payload: OrderCreatedPayload) =>
createEvent('OrderCreated', 'Order', orderId, payload),
paid: (orderId: string, payload: OrderPaidPayload) =>
createEvent('OrderPaid', 'Order', orderId, payload),
shipped: (orderId: string, payload: OrderShippedPayload) =>
createEvent('OrderShipped', 'Order', orderId, payload),
cancelled: (orderId: string, payload: OrderCancelledPayload) =>
createEvent('OrderCancelled', 'Order', orderId, payload),
};
```
## Event Bus
### In-Memory Event Bus
```typescript
// events/event-bus.ts
import { EventEmitter } from 'events';
import { DomainEvent } from './base';
type EventHandler<T = unknown> = (event: DomainEvent<T>) => Promise<void>;
class EventBus {
private emitter = new EventEmitter();
private handlers = new Map<string, EventHandler[]>();
async publish<T>(event: DomainEvent<T>): Promise<void> {
console.log(`Publishing event: ${event.type}`, event);
// Store event (for event sourcing)
await this.storeEvent(event);
// Emit to handlers
this.emitter.emit(event.type, event);
this.emitter.emit('*', event); // Wildcard for all events
}
async publishAll(events: DomainEvent[]): Promise<void> {
for (const event of events) {
await this.publish(event);
}
}
subscribe<T>(eventType: string, handler: EventHandler<T>): () => void {
const wrappedHandler = async (event: DomainEvent<T>) => {
try {
await handler(event);
} catch (error) {
console.error(`Error handling ${eventType}:`, error);
// Could emit to dead letter queue here
}
};
this.emitter.on(eventType, wrappedHandler);
// Return unsubscribe function
return () => {
this.emitter.off(eventType, wrappedHandler);
};
}
subscribeAll(handler: EventHandler): () => void {
return this.subscribe('*', handler);
}
private async storeEvent(event: DomainEvent): Promise<void> {
await db.event.create({
data: {
id: event.id,
type: event.type,
aggregateId: event.aggregateId,
aggregateType: event.aggregateType,
payload: event.payload as any,
metadata: event.metadata as any,
createdAt: event.metadata.timestamp,
},
});
}
}
export const eventBus = new EventBus();
```
### Redis-Based Event Bus
```typescript
// events/redis-event-bus.ts
import { Redis } from 'ioredis';
import { DomainEvent } from './base';
const publisher = new Redis(process.env.REDIS_URL!);
const subscriber = new Redis(process.env.REDIS_URL!);
class RedisEventBus {
private handlers = new Map<string, Set<(event: DomainEvent) => Promise<void>>>();
constructor() {
subscriber.on('message', async (channel, message) => {
const event = JSON.parse(message) as DomainEvent;
const handlers = this.handlers.get(channel) || new Set();
for (const handler of handlers) {
try {
await handler(event);
} catch (error) {
console.error(`Error handling ${event.type}:`, error);
}
}
});
}
async publish(event: DomainEvent): Promise<void> {
const channel = `events:${event.type}`;
await publisher.publish(channel, JSON.stringify(event));
// Also store in stream for replay
await publisher.xadd(
`stream:${event.aggregateType}`,
'*',
'event',
JSON.stringify(event)
);
}
subscribe(eventType: string, handler: (event: DomainEvent) => Promise<void>): () => void {
const channel = `events:${eventType}`;
if (!this.handlers.has(channel)) {
this.handlers.set(channel, new Set());
subscriber.subscribe(channel);
}
this.handlers.get(channel)!.add(handler);
return () => {
this.handlers.get(channel)?.delete(handler);
};
}
}
export const eventBus = new RedisEventBus();
```
## Event Handlers
### Handler Registration
```typescript
// handlers/order.handlers.ts
import { eventBus } from '../events/event-bus';
import { OrderEvent } from '../events/order.events';
// Email notification on order created
eventBus.subscribe<OrderCreatedPayload>('OrderCreated', async (event) => {
await emailService.send({
to: await getUserEmail(event.payload.customerId),
template: 'order-confirmation',
data: {
orderId: event.aggregateId,
items: event.payload.items,
total: event.payload.totalAmount,
},
});
});
// Update inventory on order created
eventBus.subscribe<OrderCreatedPayload>('OrderCreated', async (event) => {
for (const item of event.payload.items) {
await inventoryService.reserve(item.productId, item.quantity);
}
});
// Analytics tracking
eventBus.subscribe<OrderPaidPayload>('OrderPaid', async (event) => {
await analytics.track('order_completed', {
orderId: event.aggregateId,
amount: event.payload.amount,
paymentMethod: event.payload.method,
});
});
// Notify shipping on order paid
eventBus.subscribe<OrderPaidPayload>('OrderPaid', async (event) => {
await shippingService.createShipment(event.aggregateId);
});
// Handle cancellation
eventBus.subscribe<OrderCancelledPayload>('OrderCancelled', async (event) => {
// Release inventory
const order = await orderRepository.findById(event.aggregateId);
for (const item of order.items) {
await inventoryService.release(item.productId, item.quantity);
}
// Process refund
if (event.payload.refundAmount) {
await paymentService.refund(event.aggregateId, event.payload.refundAmount);
}
// Send cancellation email
await emailService.send({
to: await getUserEmail(order.customerId),
template: 'order-cancelled',
data: {
orderId: event.aggregateId,
reason: event.payload.reason,
},
});
});
```
## Event Sourcing
### Aggregate with Events
```typescript
// aggregates/order.aggregate.ts
import { DomainEvent } from '../eveRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.