scaling-patterns
Enterprise scaling patterns for microservices, event-driven architecture, and distributed systems
What this skill does
# Scaling Patterns Skill
## Purpose
Design and implement scalable distributed systems with proven patterns.
## Microservices Architecture
### Service Decomposition
```
┌─────────────────────────────────────────────────────────────────┐
│ API Gateway │
│ (Authentication, Rate Limiting, Routing, Load Balancing) │
└─────────────────────────┬───────────────────────────────────────┘
│
┌────────────────┼────────────────┐
│ │ │
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
│ User │ │ Order │ │ Product │
│ Service │ │ Service │ │ Service │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
│ User DB │ │Order DB │ │Prod. DB │
└─────────┘ └─────────┘ └─────────┘
```
### Service Communication
```typescript
// Synchronous (REST/gRPC)
class OrderService {
constructor(
private userClient: UserServiceClient,
private productClient: ProductServiceClient,
) {}
async createOrder(userId: string, productId: string) {
// Validate user exists
const user = await this.userClient.getUser(userId);
if (!user) throw new NotFoundError('User not found');
// Check product availability
const product = await this.productClient.getProduct(productId);
if (!product.available) throw new ConflictError('Product unavailable');
return this.orderRepository.create({ userId, productId });
}
}
// Asynchronous (Event-driven)
class OrderService {
async createOrder(userId: string, productId: string) {
const order = await this.orderRepository.create({
userId,
productId,
status: 'pending',
});
// Emit event instead of sync call
await this.eventBus.publish('order.created', {
orderId: order.id,
userId,
productId,
timestamp: new Date(),
});
return order;
}
}
```
## SAGA Pattern
### Choreography-based SAGA
```typescript
// Event handlers in each service
// Order Service
class OrderEventHandler {
@EventHandler('order.created')
async onOrderCreated(event: OrderCreatedEvent) {
// Emit next event in chain
await this.eventBus.publish('payment.requested', {
orderId: event.orderId,
amount: event.total,
});
}
@EventHandler('payment.failed')
async onPaymentFailed(event: PaymentFailedEvent) {
// Compensating transaction
await this.orderRepository.update(event.orderId, { status: 'cancelled' });
await this.eventBus.publish('order.cancelled', { orderId: event.orderId });
}
}
// Payment Service
class PaymentEventHandler {
@EventHandler('payment.requested')
async onPaymentRequested(event: PaymentRequestedEvent) {
try {
await this.paymentGateway.charge(event.amount);
await this.eventBus.publish('payment.completed', {
orderId: event.orderId,
});
} catch (error) {
await this.eventBus.publish('payment.failed', {
orderId: event.orderId,
reason: error.message,
});
}
}
}
```
### Orchestration-based SAGA
```typescript
class OrderSaga {
private steps: SagaStep[] = [
{
name: 'reserveInventory',
execute: (ctx) => this.inventoryService.reserve(ctx.productId, ctx.quantity),
compensate: (ctx) => this.inventoryService.release(ctx.productId, ctx.quantity),
},
{
name: 'processPayment',
execute: (ctx) => this.paymentService.charge(ctx.userId, ctx.amount),
compensate: (ctx) => this.paymentService.refund(ctx.paymentId),
},
{
name: 'createShipment',
execute: (ctx) => this.shippingService.create(ctx.orderId, ctx.address),
compensate: (ctx) => this.shippingService.cancel(ctx.shipmentId),
},
];
async execute(context: OrderContext) {
const completedSteps: SagaStep[] = [];
for (const step of this.steps) {
try {
const result = await step.execute(context);
context = { ...context, ...result };
completedSteps.push(step);
} catch (error) {
// Rollback in reverse order
for (const completedStep of completedSteps.reverse()) {
await completedStep.compensate(context);
}
throw new SagaExecutionError(step.name, error);
}
}
return context;
}
}
```
## Circuit Breaker Pattern
```typescript
enum CircuitState {
CLOSED = 'CLOSED',
OPEN = 'OPEN',
HALF_OPEN = 'HALF_OPEN',
}
class CircuitBreaker {
private state = CircuitState.CLOSED;
private failureCount = 0;
private successCount = 0;
private lastFailureTime?: Date;
constructor(
private readonly options: {
failureThreshold: number; // Failures before opening
successThreshold: number; // Successes in half-open to close
timeout: number; // Time in open state before half-open
}
) {}
async execute<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === CircuitState.OPEN) {
if (this.shouldAttemptReset()) {
this.state = CircuitState.HALF_OPEN;
} else {
throw new CircuitBreakerOpenError();
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private onSuccess() {
this.failureCount = 0;
if (this.state === CircuitState.HALF_OPEN) {
this.successCount++;
if (this.successCount >= this.options.successThreshold) {
this.state = CircuitState.CLOSED;
this.successCount = 0;
}
}
}
private onFailure() {
this.failureCount++;
this.lastFailureTime = new Date();
if (this.failureCount >= this.options.failureThreshold) {
this.state = CircuitState.OPEN;
}
}
private shouldAttemptReset(): boolean {
if (!this.lastFailureTime) return false;
const elapsed = Date.now() - this.lastFailureTime.getTime();
return elapsed >= this.options.timeout;
}
}
// Usage
const userServiceBreaker = new CircuitBreaker({
failureThreshold: 5,
successThreshold: 3,
timeout: 30000,
});
async function getUser(id: string) {
return userServiceBreaker.execute(() => userService.get(id));
}
```
## Event Sourcing & CQRS
```typescript
// Event Store
interface DomainEvent {
id: string;
aggregateId: string;
aggregateType: string;
eventType: string;
payload: unknown;
timestamp: Date;
version: number;
}
class EventStore {
async append(events: DomainEvent[]): Promise<void> {
await this.db.transaction(async (tx) => {
for (const event of events) {
await tx.insert('events', event);
}
});
// Publish to message bus
for (const event of events) {
await this.messageBus.publish(event.eventType, event);
}
}
async getEvents(aggregateId: string, fromVersion = 0): Promise<DomainEvent[]> {
return this.db.query(
'SELECT * FROM events WHERE aggregate_id = ? AND version > ? ORDER BY version',
[aggregateId, fromVersion]
);
}
}
// Aggregate
class OrderAggregate {
private events: DomainEvent[] = [];
private state: OrderState = { status: 'draft', items: [] };
static async load(eventStore: EventStore, id: string): Promise<OrderAggregate> {
const aggregate = new OrderAggregate();
const events = await eventStore.getEvents(id);
events.forEach((e) => aggregate.apply(e, false));
return aggregate;
}
addItem(productId: string, quantity: number): void {
this.apply({
eventType: 'ItemAdded',
payload: { productId, quantity },
});
}
submit(): void {
if (this.state.items.length === 0) {
throw new Error('Cannot submit empty order');
}
this.apply({ eventType: 'OrderSubmitted', payload: {} });
}
private apply(event: Partial<DomainEvent>, isNew = true): void {
// Update state based on event
switch (event.Related 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.