.do
Architecture

System Design

Architecture principles for Business-as-Code applications

Architectural principles and patterns for Business-as-Code systems.

Core Architecture

Business-as-Code applications follow a layered, event-driven architecture:

graph TB subgraph Presentation["Presentation Layer"] UI[Web/Mobile UI] API[API Gateway] end subgraph Application["Application Layer"] BL[Business Logic<br/>Event Handlers] WF[Workflows] AI[AI Engine] end subgraph Domain["Domain Layer"] Entities[Semantic Entities] Relations[Relationships] Events[Domain Events] end subgraph Infrastructure["Infrastructure Layer"] DB[(Graph Database)] Queue[Event Queue] Storage[Object Storage] Cache[Cache Layer] end UI --> API API --> BL BL --> WF BL --> AI WF --> Events Events --> Queue Queue --> BL BL --> Entities Entities --> Relations Relations --> DB Events --> DB

Key Principles

1. Semantic-First

Everything is modeled using semantic types:

// Good: Semantic types
const customer = await $.Person.create({
  $type: 'Person',
  givenName: 'Alice',
  email: '[email protected]',
})

// Avoid: Custom types
const user = { name: 'Alice', email: '[email protected]' }

2. Event-Driven

State changes trigger events, events trigger workflows:

// Events coordinate system behavior
on($.Order.created, handleOrderCreated)
on($.Payment.processed, handlePaymentProcessed)
on($.Shipment.created, handleShipmentCreated)

3. AI-Native

AI is embedded throughout, not bolted on:

// AI makes business decisions
const decision = await ai.decide('pricing', context)
const recommendations = await ai.recommend({ type, for, context })

4. Distributed by Default

Components are loosely coupled and independently deployable:

  • Event-driven communication
  • Async-first operations
  • Service independence
  • Horizontal scalability

Component Architecture

Entities & Relationships

// Entity storage
interface EntityStore {
  create(type: string, data: any): Promise<Entity>
  get(type: string, id: string): Promise<Entity>
  update(type: string, id: string, data: any): Promise<Entity>
  delete(type: string, id: string): Promise<void>
  list(type: string, query: Query): Promise<Entity[]>
}

// Relationship storage
interface RelationStore {
  relate(subject: Entity, predicate: string, object: Entity): Promise<void>
  unrelate(subject: Entity, predicate: string, object: Entity): Promise<void>
  related(subject: Entity, predicate: string, type: string): Promise<Entity[]>
  query(pattern: GraphPattern): Promise<Entity[]>
}

Event System

// Event bus
interface EventBus {
  on(eventType: string, handler: EventHandler): void
  off(eventType: string, handler: EventHandler): void
  emit(eventType: string, data: any): Promise<void>
}

// Event store (for event sourcing)
interface EventStore {
  append(aggregateId: string, event: Event): Promise<void>
  getEvents(aggregateId: string): Promise<Event[]>
  subscribe(eventType: string, handler: EventHandler): void
}

AI Integration

// AI service interface
interface AIService {
  generate(type: string, context: any): Promise<any>
  decide(strategy: string, context: any): Promise<Decision>
  recommend(params: RecommendParams): Promise<any[]>
  analyze(metric: string, data: any): Promise<Analysis>
}

Data Flow

Typical request flow through the system:

sequenceDiagram participant C as Client participant A as API Gateway participant B as Business Logic participant AI as AI Engine participant E as Event Bus participant D as Database C->>A: HTTP Request A->>B: Route to Handler B->>D: Query Data D-->>B: Return Data B->>AI: Request Decision AI-->>B: Return Decision B->>D: Update State B->>E: Emit Event E-->>B: Trigger Handlers B-->>A: Response A-->>C: HTTP Response

Scalability Patterns

Horizontal Scaling

  • Stateless application servers
  • Distributed event processing
  • Sharded databases
  • CDN for static assets

Caching Strategy

// Multi-layer caching
interface CacheStrategy {
  // L1: In-memory (milliseconds)
  memory: MemoryCache

  // L2: Redis (sub-millisecond)
  distributed: RedisCache

  // L3: CDN (edge caching)
  cdn: CDNCache
}

Async Processing

// Long-running operations
on($.Order.created, async (order) => {
  // Quick acknowledgment
  await db.update($.Order, order.$id, { status: 'processing' })

  // Async processing
  await queue.enqueue('order-fulfillment', order)

  return { status: 'accepted' }
})

Security Architecture

Authentication & Authorization

// JWT-based auth
interface AuthService {
  authenticate(credentials: Credentials): Promise<Token>
  authorize(token: Token, resource: string, action: string): Promise<boolean>
  refresh(token: Token): Promise<Token>
}

// Role-based access control
const permissions = {
  admin: ['*'],
  seller: ['order:read', 'order:update', 'product:*'],
  customer: ['order:read', 'profile:*'],
}

Data Protection

  • Encryption at rest (AES-256)
  • Encryption in transit (TLS 1.3)
  • PII tokenization
  • Audit logging

Monitoring & Observability

Metrics

// Track key metrics
interface Metrics {
  // Application metrics
  requestRate: number
  errorRate: number
  p95Latency: number

  // Business metrics
  ordersPerSecond: number
  revenue: number
  activeUsers: number

  // AI metrics
  aiDecisionAccuracy: number
  aiLatency: number
}

Logging

// Structured logging
log.info('Order processed', {
  orderId: order.$id,
  customer: order.customer.$id,
  amount: order.totalPrice,
  duration: processingTime,
})

Tracing

// Distributed tracing
const span = tracer.startSpan('process-order')
span.setTag('order.id', order.$id)

try {
  await processOrder(order)
  span.setTag('success', true)
} catch (error) {
  span.setTag('error', true)
  span.log({ error: error.message })
} finally {
  span.finish()
}

Best Practices

1. Design for Failure

  • Circuit breakers
  • Retry with backoff
  • Graceful degradation
  • Fallback strategies

2. Keep State Minimal

  • Event sourcing
  • CQRS for reads
  • Cache invalidation

3. Optimize for Change

  • Feature flags
  • Canary deployments
  • A/B testing infrastructure

4. Monitor Everything

  • Application metrics
  • Business metrics
  • AI performance
  • User experience

Summary

Business-as-Code architecture is:

  • Semantic - Everything has meaning
  • Event-Driven - Async by default
  • AI-Native - Intelligence embedded
  • Distributed - Scale horizontally
  • Observable - Monitor and learn

Next: Deployment →