# Motia Integration Patterns

## Executive Summary

This document provides comprehensive patterns and strategies for integrating Motia into existing development workflows, particularly focusing on NX monorepo environments, CI/CD pipelines, third-party services, and modern toolchains. Motia's unified architecture enables powerful integration patterns that consolidate backend infrastructure while maintaining compatibility with existing systems.

**Key Integration Areas:**
- NX Monorepo Integration: Workspace structure, build pipelines, dependency management
- CI/CD Pipeline Integration: GitHub Actions, GitLab CI, deployment automation
- Third-Party Services: Databases, message queues, authentication providers, APIs
- Frontend Integration: REST APIs, WebSockets, Server-Sent Events, GraphQL
- Development Tools: TypeScript, testing frameworks, linting, code generation
- Infrastructure: Docker, Kubernetes, cloud platforms, monitoring services

**Critical Success Factors:**
- Leverage NX's build system while integrating Motia's development server
- Implement gradual migration patterns (Strangler Fig) for existing backends
- Use Motia as orchestration layer while preserving domain logic
- Establish clear boundaries between Motia framework and business logic
- Maintain compatibility with existing frontend applications

---

## Current State Analysis

### Integration Context

#### Typical Technology Stack (Pre-Motia)

**Backend Services:**
- **API Framework**: Nest.js, Express, Fastify
- **Workflow Engine**: Temporal, Apache Airflow
- **Background Jobs**: BullMQ, Celery, Sidekiq
- **Message Queue**: RabbitMQ, Redis, Kafka
- **State Management**: Redis, PostgreSQL
- **Monitoring**: Datadog, New Relic, Prometheus

**Infrastructure:**
- **Monorepo**: NX, Turborepo, Lerna
- **CI/CD**: GitHub Actions, GitLab CI, Jenkins
- **Deployment**: Docker, Kubernetes, AWS ECS
- **Databases**: PostgreSQL, MongoDB, MySQL

**Motia Consolidation Opportunity:**
Motia can replace 3-5 separate frameworks and services with a unified runtime, simplifying architecture while maintaining functionality.

#### Migration Challenges

1. **Existing Codebases**: Gradual migration from established frameworks
2. **Team Knowledge**: Learning curve for new patterns and architecture
3. **Production Risk**: Minimizing disruption during transition
4. **Compatibility**: Maintaining existing API contracts and integrations
5. **Testing**: Adapting test suites to new framework patterns
6. **Monitoring**: Transitioning observability infrastructure

### Integration Models

#### Model 1: Greenfield (New Projects)

**Scenario**: Starting from scratch with Motia as primary backend framework

**Advantages:**
- No legacy constraints
- Can design optimal architecture
- Full leverage of Motia features
- Simplified toolchain

**Recommended For:**
- New microservices
- Internal tools
- Prototypes and MVPs
- AI-powered features

#### Model 2: Strangler Fig (Gradual Migration)

**Scenario**: Incrementally replacing existing backend services with Motia

**Advantages:**
- Minimal production risk
- Gradual team learning
- Continuous value delivery
- Ability to roll back

**Recommended For:**
- Large existing codebases
- Mission-critical systems
- Complex legacy architectures
- Risk-averse organizations

#### Model 3: Hybrid (Coexistence)

**Scenario**: Motia handles specific concerns (workflows, AI) while existing services remain

**Advantages:**
- Leverage Motia's strengths
- Preserve working systems
- Focused migration effort
- Reduced risk

**Recommended For:**
- Adding AI capabilities
- Complex workflow orchestration
- Event-driven extensions
- Background job consolidation

---

## NX Monorepo Integration Patterns

### 1. Workspace Structure

#### Recommended NX + Motia Structure

```
<workspace-root>/
├── apps/
│   ├── motia-backend/              # Main Motia application
│   │   ├── src/
│   │   │   ├── flows/
│   │   │   │   ├── api/
│   │   │   │   ├── events/
│   │   │   │   ├── cron/
│   │   │   │   └── agents/
│   │   │   ├── config/
│   │   │   └── main.ts
│   │   ├── project.json
│   │   ├── tsconfig.json
│   │   ├── Dockerfile
│   │   └── .env
│   ├── web-frontend/               # Frontend application
│   │   └── ...
│   └── legacy-api/                 # Existing API (during migration)
│       └── ...
├── libs/
│   ├── shared/
│   │   ├── types/                  # Shared TypeScript types
│   │   ├── utils/                  # Shared utilities
│   │   └── constants/              # Shared constants
│   ├── domain/
│   │   ├── users/                  # User domain logic
│   │   ├── orders/                 # Order domain logic
│   │   └── products/               # Product domain logic
│   ├── data-access/
│   │   ├── prisma/                 # Database client
│   │   ├── redis/                  # Redis client
│   │   └── external-apis/          # Third-party API clients
│   ├── motia-shared/
│   │   ├── steps/                  # Reusable Motia steps
│   │   ├── middleware/             # Custom middleware
│   │   └── testing/                # Testing utilities
│   └── api-contracts/              # API schemas (shared with frontend)
│       └── openapi/
├── tools/
│   ├── scripts/
│   └── generators/                 # Custom NX generators
├── nx.json
├── package.json
└── tsconfig.base.json
```

### 2. NX Project Configuration

#### Motia Backend Project Configuration

```json
// apps/motia-backend/project.json
{
  "name": "motia-backend",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "apps/motia-backend/src",
  "projectType": "application",
  "targets": {
    "serve": {
      "executor": "@nx/node:execute",
      "options": {
        "buildTarget": "motia-backend:build",
        "command": "npx motia dev"
      },
      "configurations": {
        "development": {
          "envFile": "apps/motia-backend/.env.development"
        },
        "production": {
          "envFile": "apps/motia-backend/.env.production"
        }
      }
    },
    "build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "options": {
        "target": "node",
        "compiler": "tsc",
        "outputPath": "dist/apps/motia-backend",
        "main": "apps/motia-backend/src/main.ts",
        "tsConfig": "apps/motia-backend/tsconfig.app.json",
        "assets": [
          "apps/motia-backend/src/assets",
          {
            "input": "apps/motia-backend",
            "glob": ".env.*",
            "output": "."
          }
        ],
        "webpackConfig": "apps/motia-backend/webpack.config.js"
      },
      "configurations": {
        "production": {
          "optimization": true,
          "extractLicenses": true,
          "sourceMap": false,
          "fileReplacements": [
            {
              "replace": "apps/motia-backend/src/config/config.ts",
              "with": "apps/motia-backend/src/config/config.prod.ts"
            }
          ]
        }
      }
    },
    "lint": {
      "executor": "@nx/linter:eslint",
      "options": {
        "lintFilePatterns": ["apps/motia-backend/**/*.ts"]
      }
    },
    "test": {
      "executor": "@nx/jest:jest",
      "outputs": ["{workspaceRoot}/coverage/apps/motia-backend"],
      "options": {
        "jestConfig": "apps/motia-backend/jest.config.ts",
        "passWithNoTests": true
      }
    },
    "docker-build": {
      "executor": "@nx/docker:build",
      "options": {
        "context": ".",
        "file": "apps/motia-backend/Dockerfile",
        "tags": ["motia-backend:latest", "motia-backend:{args.version}"]
      }
    },
    "deploy": {
      "executor": "@nx/node:execute",
      "options": {
        "command": "npx motia deploy --project=motia-backend"
      },
      "configurations": {
        "staging": {
          "command": "npx motia deploy --project=motia-backend --env=staging"
        },
        "production": {
          "command": "npx motia deploy --project=motia-backend --env=production"
        }
      }
    }
  },
  "tags": ["type:app", "scope:backend", "framework:motia"]
}
```

### 3. Shared Library Integration

#### Domain Logic Library

```typescript
// libs/domain/users/src/lib/user.service.ts
import { PrismaClient } from '@prisma/client';

export class UserService {
  constructor(private prisma: PrismaClient) {}

  async createUser(data: {
    email: string;
    name: string;
    password: string;
  }) {
    // Hash password
    const hashedPassword = await this.hashPassword(data.password);

    // Create user
    const user = await this.prisma.user.create({
      data: {
        email: data.email,
        name: data.name,
        passwordHash: hashedPassword
      }
    });

    return this.sanitizeUser(user);
  }

  async findUserByEmail(email: string) {
    const user = await this.prisma.user.findUnique({
      where: { email }
    });

    return user ? this.sanitizeUser(user) : null;
  }

  private sanitizeUser(user: any) {
    const { passwordHash, ...sanitized } = user;
    return sanitized;
  }

  private async hashPassword(password: string): Promise<string> {
    // Implementation
    return 'hashed';
  }
}

// Export for use in Motia steps
export * from './user.service';
```

#### Using Domain Logic in Motia Steps

```typescript
// apps/motia-backend/src/flows/api/users.api.ts
import { api, z } from 'motia';
import { UserService } from '@workspace/domain/users';
import { prisma } from '@workspace/data-access/prisma';

const userService = new UserService(prisma);

export const createUser = api({
  method: 'POST',
  path: '/users',

  body: z.object({
    email: z.string().email(),
    name: z.string().min(2),
    password: z.string().min(8)
  }),

  async handler({ body }) {
    // Use shared domain logic
    const user = await userService.createUser(body);

    return {
      id: user.id,
      email: user.email,
      name: user.name
    };
  }
});

export const getUser = api({
  method: 'GET',
  path: '/users/:id',

  params: z.object({
    id: z.string().uuid()
  }),

  async handler({ params }) {
    const user = await userService.findUserById(params.id);

    if (!user) {
      throw new NotFoundError('User not found');
    }

    return user;
  }
});
```

### 4. Dependency Management

#### tsconfig.json Path Mapping

```json
// tsconfig.base.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@workspace/domain/users": ["libs/domain/users/src/index.ts"],
      "@workspace/domain/orders": ["libs/domain/orders/src/index.ts"],
      "@workspace/shared/types": ["libs/shared/types/src/index.ts"],
      "@workspace/shared/utils": ["libs/shared/utils/src/index.ts"],
      "@workspace/data-access/prisma": ["libs/data-access/prisma/src/index.ts"],
      "@workspace/motia-shared": ["libs/motia-shared/src/index.ts"]
    }
  }
}
```

#### NX Dependency Graph

```json
// nx.json
{
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"]
    }
  },
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/tsconfig.spec.json",
      "!{projectRoot}/.eslintrc.json"
    ]
  },
  "tasksRunnerOptions": {
    "default": {
      "runner": "nx/tasks-runners/default",
      "options": {
        "cacheableOperations": ["build", "lint", "test"]
      }
    }
  }
}
```

### 5. Custom NX Generators

#### Generate Motia Step Generator

```typescript
// tools/generators/motia-step/index.ts
import {
  Tree,
  formatFiles,
  generateFiles,
  joinPathFragments
} from '@nx/devkit';

interface MotiaStepGeneratorSchema {
  name: string;
  type: 'api' | 'event' | 'cron' | 'agent';
  project: string;
}

export default async function (tree: Tree, options: MotiaStepGeneratorSchema) {
  const projectRoot = `apps/${options.project}/src/flows/${options.type}`;

  // Generate step file
  generateFiles(
    tree,
    joinPathFragments(__dirname, 'files'),
    projectRoot,
    {
      ...options,
      tmpl: '',
      name: options.name
    }
  );

  // Generate test file
  generateFiles(
    tree,
    joinPathFragments(__dirname, 'test-files'),
    projectRoot,
    {
      ...options,
      tmpl: '',
      name: options.name
    }
  );

  await formatFiles(tree);
}
```

**Usage:**
```bash
# Generate new API step
nx g @workspace/tools:motia-step --name=get-user --type=api --project=motia-backend

# Generate new event handler
nx g @workspace/tools:motia-step --name=user-created --type=event --project=motia-backend
```

---

## CI/CD Pipeline Integration

### 1. GitHub Actions Workflow

```yaml
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

env:
  NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }}

jobs:
  # Continuous Integration
  ci:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [18.x, 20.x]

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
          cache: 'pnpm'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Derive appropriate SHAs for base and head for `nx affected` commands
        uses: nrwl/nx-set-shas@v4

      - name: Lint affected projects
        run: npx nx affected -t lint --parallel=3

      - name: Test affected projects
        run: npx nx affected -t test --parallel=3 --coverage

      - name: Build affected projects
        run: npx nx affected -t build --parallel=3

      - name: Upload coverage reports
        uses: codecov/codecov-action@v3
        with:
          directory: ./coverage

  # Motia-specific validation
  motia-validate:
    runs-on: ubuntu-latest
    needs: ci

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Validate Motia configuration
        run: |
          cd apps/motia-backend
          npx motia validate

      - name: Run Motia tests
        run: nx test motia-backend

      - name: Build Docker image
        run: nx docker-build motia-backend

  # Continuous Deployment (Staging)
  deploy-staging:
    runs-on: ubuntu-latest
    needs: [ci, motia-validate]
    if: github.ref == 'refs/heads/develop'

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build Motia backend
        run: nx build motia-backend --configuration=production

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

      - name: Build and push Docker image
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          ECR_REPOSITORY: motia-backend
          IMAGE_TAG: ${{ github.sha }}
        run: |
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG -f apps/motia-backend/Dockerfile .
          docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:staging
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:staging

      - name: Deploy to ECS
        run: |
          aws ecs update-service \
            --cluster motia-staging \
            --service motia-backend \
            --force-new-deployment

      - name: Wait for deployment
        run: |
          aws ecs wait services-stable \
            --cluster motia-staging \
            --services motia-backend

      - name: Run smoke tests
        run: |
          npm run test:smoke:staging

  # Continuous Deployment (Production)
  deploy-production:
    runs-on: ubuntu-latest
    needs: [ci, motia-validate]
    if: github.ref == 'refs/heads/main'
    environment:
      name: production
      url: https://api.production.example.com

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build Motia backend
        run: nx build motia-backend --configuration=production

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

      - name: Build and push Docker image
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          ECR_REPOSITORY: motia-backend
          IMAGE_TAG: ${{ github.sha }}
        run: |
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG -f apps/motia-backend/Dockerfile .
          docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:production
          docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:latest
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:production
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest

      - name: Deploy to ECS (Blue/Green)
        run: |
          aws ecs update-service \
            --cluster motia-production \
            --service motia-backend \
            --force-new-deployment \
            --deployment-configuration "maximumPercent=200,minimumHealthyPercent=100"

      - name: Wait for deployment
        run: |
          aws ecs wait services-stable \
            --cluster motia-production \
            --services motia-backend

      - name: Run smoke tests
        run: |
          npm run test:smoke:production

      - name: Notify deployment
        uses: 8398a7/action-slack@v3
        with:
          status: ${{ job.status }}
          text: 'Motia backend deployed to production'
          webhook_url: ${{ secrets.SLACK_WEBHOOK }}
```

### 2. GitLab CI Integration

```yaml
# .gitlab-ci.yml
stages:
  - install
  - lint
  - test
  - build
  - deploy

variables:
  NX_BRANCH: $CI_COMMIT_REF_NAME
  NX_CLOUD_ACCESS_TOKEN: $NX_CLOUD_ACCESS_TOKEN

# Cache configuration
.cache_template: &cache_config
  cache:
    key:
      files:
        - pnpm-lock.yaml
    paths:
      - .pnpm-store
      - node_modules

# Install dependencies
install:
  stage: install
  <<: *cache_config
  script:
    - npm install -g pnpm
    - pnpm config set store-dir .pnpm-store
    - pnpm install --frozen-lockfile
  artifacts:
    paths:
      - node_modules
      - .pnpm-store
    expire_in: 1 day

# Lint affected projects
lint:
  stage: lint
  <<: *cache_config
  needs: [install]
  script:
    - npx nx affected -t lint --base=origin/main --head=HEAD

# Test affected projects
test:
  stage: test
  <<: *cache_config
  needs: [install]
  script:
    - npx nx affected -t test --base=origin/main --head=HEAD --coverage
  coverage: '/Statements\s*:\s*([^%]+)/'
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage/cobertura-coverage.xml

# Build affected projects
build:
  stage: build
  <<: *cache_config
  needs: [install, lint, test]
  script:
    - npx nx affected -t build --base=origin/main --head=HEAD --configuration=production
  artifacts:
    paths:
      - dist
    expire_in: 1 day

# Deploy to staging
deploy:staging:
  stage: deploy
  needs: [build]
  only:
    - develop
  script:
    - cd apps/motia-backend
    - npx motia deploy --env=staging
  environment:
    name: staging
    url: https://api.staging.example.com

# Deploy to production
deploy:production:
  stage: deploy
  needs: [build]
  only:
    - main
  when: manual
  script:
    - cd apps/motia-backend
    - npx motia deploy --env=production
  environment:
    name: production
    url: https://api.production.example.com
```

### 3. Deployment Automation Scripts

```typescript
// tools/scripts/deploy-motia.ts
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

interface DeployOptions {
  environment: 'development' | 'staging' | 'production';
  project: string;
  skipTests?: boolean;
  dryRun?: boolean;
}

async function deployMotia(options: DeployOptions) {
  console.log(`Deploying ${options.project} to ${options.environment}...`);

  // 1. Load environment-specific configuration
  const envFile = `.env.${options.environment}`;
  if (!fs.existsSync(envFile)) {
    throw new Error(`Environment file not found: ${envFile}`);
  }

  // 2. Run tests (unless skipped)
  if (!options.skipTests) {
    console.log('Running tests...');
    execSync(`nx test ${options.project}`, { stdio: 'inherit' });
  }

  // 3. Build project
  console.log('Building project...');
  execSync(
    `nx build ${options.project} --configuration=${options.environment}`,
    { stdio: 'inherit' }
  );

  // 4. Build Docker image
  console.log('Building Docker image...');
  const imageTag = `${options.project}:${options.environment}-${Date.now()}`;
  execSync(`nx docker-build ${options.project} --tag=${imageTag}`, {
    stdio: 'inherit'
  });

  // 5. Deploy (if not dry run)
  if (!options.dryRun) {
    console.log('Deploying to environment...');

    if (options.environment === 'production') {
      // Use MotiaHub for production
      execSync(
        `npx motia deploy --project=${options.project} --env=production`,
        { stdio: 'inherit' }
      );
    } else {
      // Use self-hosted for staging
      execSync(`./deploy-to-ecs.sh ${options.environment} ${imageTag}`, {
        stdio: 'inherit'
      });
    }

    console.log('Deployment successful!');
  } else {
    console.log('Dry run complete. No deployment performed.');
  }
}

// Parse command line arguments
const args = process.argv.slice(2);
const options: DeployOptions = {
  environment: (args[0] as any) || 'development',
  project: args[1] || 'motia-backend',
  skipTests: args.includes('--skip-tests'),
  dryRun: args.includes('--dry-run')
};

deployMotia(options).catch((error) => {
  console.error('Deployment failed:', error);
  process.exit(1);
});
```

---

## Third-Party Service Integration

### 1. Database Integration

#### Prisma ORM Integration

```typescript
// libs/data-access/prisma/src/lib/prisma.service.ts
import { PrismaClient } from '@prisma/client';

export class PrismaService extends PrismaClient {
  constructor() {
    super({
      datasources: {
        db: {
          url: process.env.DATABASE_URL
        }
      },
      log:
        process.env.NODE_ENV === 'development'
          ? ['query', 'info', 'warn', 'error']
          : ['error'],
      errorFormat: 'minimal'
    });
  }

  async onModuleInit() {
    await this.$connect();
  }

  async onModuleDestroy() {
    await this.$disconnect();
  }

  // Helper methods
  async healthCheck(): Promise<boolean> {
    try {
      await this.$queryRaw`SELECT 1`;
      return true;
    } catch {
      return false;
    }
  }

  // Transaction wrapper
  async transaction<T>(fn: (tx: PrismaClient) => Promise<T>): Promise<T> {
    return this.$transaction(fn);
  }
}

export const prisma = new PrismaService();
```

#### Using Prisma in Motia Steps

```typescript
// apps/motia-backend/src/flows/api/orders.api.ts
import { api, z, emit } from 'motia';
import { prisma } from '@workspace/data-access/prisma';

export const createOrder = api({
  method: 'POST',
  path: '/orders',

  body: z.object({
    userId: z.string().uuid(),
    items: z.array(
      z.object({
        productId: z.string().uuid(),
        quantity: z.number().int().positive()
      })
    )
  }),

  async handler({ body }) {
    // Use Prisma transaction
    const order = await prisma.transaction(async (tx) => {
      // 1. Create order
      const newOrder = await tx.order.create({
        data: {
          userId: body.userId,
          status: 'pending',
          items: {
            create: body.items
          }
        },
        include: {
          items: {
            include: {
              product: true
            }
          }
        }
      });

      // 2. Update inventory
      for (const item of body.items) {
        await tx.product.update({
          where: { id: item.productId },
          data: {
            stock: {
              decrement: item.quantity
            }
          }
        });
      }

      return newOrder;
    });

    // Emit event for downstream processing
    await emit('order.created', {
      orderId: order.id,
      userId: body.userId,
      total: order.items.reduce(
        (sum, item) => sum + item.product.price * item.quantity,
        0
      )
    });

    return order;
  }
});
```

### 2. Redis Integration

```typescript
// libs/data-access/redis/src/lib/redis.service.ts
import Redis, { RedisOptions } from 'ioredis';

export class RedisService {
  private client: Redis;
  private subscriber: Redis;

  constructor() {
    const options: RedisOptions = {
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379'),
      password: process.env.REDIS_PASSWORD,
      db: parseInt(process.env.REDIS_DB || '0'),
      maxRetriesPerRequest: 3,
      enableReadyCheck: true,
      lazyConnect: true
    };

    this.client = new Redis(options);
    this.subscriber = new Redis(options);
  }

  async connect() {
    await Promise.all([this.client.connect(), this.subscriber.connect()]);
  }

  async disconnect() {
    await Promise.all([this.client.disconnect(), this.subscriber.disconnect()]);
  }

  // Cache methods
  async get<T>(key: string): Promise<T | null> {
    const value = await this.client.get(key);
    return value ? JSON.parse(value) : null;
  }

  async set(key: string, value: any, ttl?: number): Promise<void> {
    const serialized = JSON.stringify(value);
    if (ttl) {
      await this.client.setex(key, ttl, serialized);
    } else {
      await this.client.set(key, serialized);
    }
  }

  async delete(key: string): Promise<void> {
    await this.client.del(key);
  }

  // Pub/Sub methods
  async publish(channel: string, message: any): Promise<void> {
    await this.client.publish(channel, JSON.stringify(message));
  }

  async subscribe(
    channel: string,
    handler: (message: any) => void
  ): Promise<void> {
    await this.subscriber.subscribe(channel);

    this.subscriber.on('message', (ch, msg) => {
      if (ch === channel) {
        handler(JSON.parse(msg));
      }
    });
  }

  // Health check
  async healthCheck(): Promise<boolean> {
    try {
      await this.client.ping();
      return true;
    } catch {
      return false;
    }
  }
}

export const redis = new RedisService();
```

### 3. Authentication Provider Integration

#### Auth0 Integration

```typescript
// libs/shared/auth/src/lib/auth0.service.ts
import { auth } from 'express-openid-connect';
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';

export class Auth0Service {
  private jwksClient: jwksClient.JwksClient;

  constructor() {
    this.jwksClient = jwksClient({
      jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
      cache: true,
      rateLimit: true
    });
  }

  // Verify JWT token
  async verifyToken(token: string): Promise<any> {
    return new Promise((resolve, reject) => {
      jwt.verify(
        token,
        this.getKey.bind(this),
        {
          audience: process.env.AUTH0_AUDIENCE,
          issuer: `https://${process.env.AUTH0_DOMAIN}/`,
          algorithms: ['RS256']
        },
        (err, decoded) => {
          if (err) {
            reject(err);
          } else {
            resolve(decoded);
          }
        }
      );
    });
  }

  private getKey(header: any, callback: any) {
    this.jwksClient.getSigningKey(header.kid, (err, key) => {
      if (err) {
        callback(err);
      } else {
        const signingKey = key?.getPublicKey();
        callback(null, signingKey);
      }
    });
  }

  // Get user info
  async getUserInfo(accessToken: string): Promise<any> {
    const response = await fetch(
      `https://${process.env.AUTH0_DOMAIN}/userinfo`,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      }
    );

    if (!response.ok) {
      throw new Error('Failed to fetch user info');
    }

    return response.json();
  }
}

export const auth0 = new Auth0Service();
```

#### Auth Middleware for Motia

```typescript
// libs/motia-shared/src/lib/middleware/auth.middleware.ts
import { api } from 'motia';
import { auth0 } from '@workspace/shared/auth';

export const requireAuth = async (req: any) => {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    throw new UnauthorizedError('Missing or invalid authorization header');
  }

  const token = authHeader.substring(7);

  try {
    const decoded = await auth0.verifyToken(token);

    // Attach user to request
    req.user = {
      id: decoded.sub,
      email: decoded.email,
      roles: decoded['https://app.example.com/roles'] || []
    };

    return req;
  } catch (error) {
    throw new UnauthorizedError('Invalid token');
  }
};

// Use in Motia steps
export const getProfile = api({
  method: 'GET',
  path: '/profile',

  // Apply middleware
  middleware: [requireAuth],

  async handler({ req }) {
    // req.user is available due to middleware
    const user = await prisma.user.findUnique({
      where: { id: req.user.id }
    });

    return user;
  }
});
```

### 4. External API Integration

#### Stripe Payment Integration

```typescript
// libs/data-access/external-apis/src/lib/stripe.service.ts
import Stripe from 'stripe';

export class StripeService {
  private stripe: Stripe;

  constructor() {
    this.stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
      apiVersion: '2023-10-16',
      typescript: true
    });
  }

  async createPaymentIntent(amount: number, currency: string = 'usd') {
    return await this.stripe.paymentIntents.create({
      amount: Math.round(amount * 100), // Convert to cents
      currency,
      automatic_payment_methods: {
        enabled: true
      }
    });
  }

  async createCustomer(email: string, name: string) {
    return await this.stripe.customers.create({
      email,
      name
    });
  }

  async createSubscription(customerId: string, priceId: string) {
    return await this.stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: priceId }],
      payment_behavior: 'default_incomplete',
      payment_settings: { save_default_payment_method: 'on_subscription' },
      expand: ['latest_invoice.payment_intent']
    });
  }

  async handleWebhook(payload: string, signature: string) {
    try {
      const event = this.stripe.webhooks.constructEvent(
        payload,
        signature,
        process.env.STRIPE_WEBHOOK_SECRET!
      );

      return event;
    } catch (error) {
      throw new Error('Invalid webhook signature');
    }
  }
}

export const stripe = new StripeService();
```

#### Using Stripe in Motia Steps

```typescript
// apps/motia-backend/src/flows/api/payments.api.ts
import { api, z, emit } from 'motia';
import { stripe } from '@workspace/data-access/external-apis';
import { requireAuth } from '@workspace/motia-shared/middleware';

export const createPayment = api({
  method: 'POST',
  path: '/payments',

  middleware: [requireAuth],

  body: z.object({
    amount: z.number().positive(),
    currency: z.string().default('usd')
  }),

  async handler({ body, req }) {
    // Create payment intent
    const paymentIntent = await stripe.createPaymentIntent(
      body.amount,
      body.currency
    );

    // Store in database
    const payment = await prisma.payment.create({
      data: {
        userId: req.user.id,
        amount: body.amount,
        currency: body.currency,
        stripePaymentIntentId: paymentIntent.id,
        status: 'pending'
      }
    });

    // Emit event
    await emit('payment.initiated', {
      paymentId: payment.id,
      userId: req.user.id,
      amount: body.amount
    });

    return {
      paymentId: payment.id,
      clientSecret: paymentIntent.client_secret
    };
  }
});

// Stripe webhook handler
export const stripeWebhook = api({
  method: 'POST',
  path: '/webhooks/stripe',

  // Raw body needed for signature verification
  rawBody: true,

  async handler({ req }) {
    const signature = req.headers['stripe-signature'] as string;
    const event = await stripe.handleWebhook(req.rawBody, signature);

    // Handle different event types
    switch (event.type) {
      case 'payment_intent.succeeded':
        await emit('payment.succeeded', {
          paymentIntentId: event.data.object.id
        });
        break;

      case 'payment_intent.payment_failed':
        await emit('payment.failed', {
          paymentIntentId: event.data.object.id,
          error: event.data.object.last_payment_error?.message
        });
        break;

      default:
        console.log(`Unhandled event type: ${event.type}`);
    }

    return { received: true };
  }
});
```

---

## Frontend Integration Patterns

### 1. REST API Integration

#### Type-Safe API Client

```typescript
// libs/api-contracts/src/lib/api-client.ts
import axios, { AxiosInstance } from 'axios';

export interface User {
  id: string;
  email: string;
  name: string;
  createdAt: string;
}

export interface CreateUserRequest {
  email: string;
  name: string;
  password: string;
}

export class ApiClient {
  private client: AxiosInstance;

  constructor(baseURL: string) {
    this.client = axios.create({
      baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // Add auth interceptor
    this.client.interceptors.request.use((config) => {
      const token = localStorage.getItem('access_token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

    // Add error interceptor
    this.client.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          // Redirect to login
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }

  // Users API
  async getUser(id: string): Promise<User> {
    const response = await this.client.get<User>(`/users/${id}`);
    return response.data;
  }

  async createUser(data: CreateUserRequest): Promise<User> {
    const response = await this.client.post<User>('/users', data);
    return response.data;
  }

  async listUsers(page: number = 1, limit: number = 10): Promise<User[]> {
    const response = await this.client.get<User[]>('/users', {
      params: { page, limit }
    });
    return response.data;
  }

  // Orders API
  async createOrder(items: Array<{ productId: string; quantity: number }>) {
    const response = await this.client.post('/orders', { items });
    return response.data;
  }

  async getOrder(id: string) {
    const response = await this.client.get(`/orders/${id}`);
    return response.data;
  }
}

// Export singleton instance
export const apiClient = new ApiClient(
  process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'
);
```

#### React Hook Integration

```typescript
// apps/web-frontend/src/hooks/useApi.ts
import { useState, useEffect } from 'react';
import { apiClient } from '@workspace/api-contracts';

export function useUser(userId: string) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let mounted = true;

    async function fetchUser() {
      try {
        setLoading(true);
        const data = await apiClient.getUser(userId);
        if (mounted) {
          setUser(data);
          setError(null);
        }
      } catch (err) {
        if (mounted) {
          setError(err);
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    }

    fetchUser();

    return () => {
      mounted = false;
    };
  }, [userId]);

  return { user, loading, error };
}

// Usage in component
function UserProfile({ userId }) {
  const { user, loading, error } = useUser(userId);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}
```

### 2. WebSocket Integration

#### WebSocket Step in Motia

```typescript
// apps/motia-backend/src/flows/websocket/chat.ws.ts
import { websocket } from 'motia';
import { z } from 'zod';

export const chatRoom = websocket({
  path: '/chat/:roomId',

  params: z.object({
    roomId: z.string()
  }),

  // Handle new connection
  async onConnect({ socket, params }) {
    console.log(`User connected to room ${params.roomId}`);

    // Join room
    socket.join(params.roomId);

    // Send welcome message
    socket.emit('message', {
      type: 'system',
      content: 'Welcome to the chat room!'
    });

    // Broadcast to others in room
    socket.to(params.roomId).emit('user-joined', {
      socketId: socket.id,
      timestamp: new Date()
    });
  },

  // Handle incoming messages
  async onMessage({ socket, params, message }) {
    const parsed = JSON.parse(message);

    // Validate message
    if (!parsed.content || typeof parsed.content !== 'string') {
      socket.emit('error', { message: 'Invalid message format' });
      return;
    }

    // Store message in database
    const savedMessage = await prisma.message.create({
      data: {
        roomId: params.roomId,
        content: parsed.content,
        userId: socket.data.userId
      },
      include: {
        user: true
      }
    });

    // Broadcast to all in room
    socket.to(params.roomId).emit('message', {
      id: savedMessage.id,
      content: savedMessage.content,
      user: {
        id: savedMessage.user.id,
        name: savedMessage.user.name
      },
      timestamp: savedMessage.createdAt
    });
  },

  // Handle disconnection
  async onDisconnect({ socket, params }) {
    console.log(`User disconnected from room ${params.roomId}`);

    // Notify others
    socket.to(params.roomId).emit('user-left', {
      socketId: socket.id,
      timestamp: new Date()
    });
  }
});
```

#### Frontend WebSocket Client

```typescript
// apps/web-frontend/src/services/websocket.ts
import { io, Socket } from 'socket.io-client';

export class WebSocketClient {
  private socket: Socket | null = null;

  connect(roomId: string) {
    this.socket = io(`${process.env.NEXT_PUBLIC_WS_URL}/chat/${roomId}`, {
      auth: {
        token: localStorage.getItem('access_token')
      },
      transports: ['websocket']
    });

    return this.socket;
  }

  disconnect() {
    this.socket?.disconnect();
    this.socket = null;
  }

  sendMessage(content: string) {
    if (!this.socket) {
      throw new Error('Socket not connected');
    }

    this.socket.emit('message', { content });
  }

  onMessage(callback: (message: any) => void) {
    this.socket?.on('message', callback);
  }

  onUserJoined(callback: (data: any) => void) {
    this.socket?.on('user-joined', callback);
  }

  onUserLeft(callback: (data: any) => void) {
    this.socket?.on('user-left', callback);
  }
}

// React hook
import { useEffect, useState } from 'react';

export function useChatRoom(roomId: string) {
  const [ws, setWs] = useState<WebSocketClient | null>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    const client = new WebSocketClient();
    const socket = client.connect(roomId);

    socket.on('connect', () => setConnected(true));
    socket.on('disconnect', () => setConnected(false));

    client.onMessage((message) => {
      setMessages((prev) => [...prev, message]);
    });

    setWs(client);

    return () => {
      client.disconnect();
    };
  }, [roomId]);

  const sendMessage = (content: string) => {
    ws?.sendMessage(content);
  };

  return { messages, connected, sendMessage };
}
```

### 3. Server-Sent Events (SSE)

#### SSE Step in Motia

```typescript
// apps/motia-backend/src/flows/api/notifications.api.ts
import { api, emit } from 'motia';

export const notificationStream = api({
  method: 'GET',
  path: '/notifications/stream',

  streaming: true,

  middleware: [requireAuth],

  async handler({ req, stream }) {
    const userId = req.user.id;

    // Send initial event
    stream.write({
      type: 'connected',
      timestamp: new Date()
    });

    // Subscribe to user-specific events
    const unsubscribe = await subscribe(
      `notifications:${userId}`,
      (notification) => {
        stream.write({
          type: 'notification',
          data: notification
        });
      }
    );

    // Handle client disconnect
    req.on('close', () => {
      unsubscribe();
      stream.end();
    });

    // Keep connection alive with periodic heartbeat
    const heartbeat = setInterval(() => {
      stream.write({
        type: 'heartbeat',
        timestamp: new Date()
      });
    }, 30000);

    req.on('close', () => {
      clearInterval(heartbeat);
    });
  }
});

// Emit notifications from other steps
export const createNotification = async (userId: string, message: string) => {
  await emit(`notifications:${userId}`, {
    id: crypto.randomUUID(),
    message,
    timestamp: new Date()
  });
};
```

#### Frontend SSE Client

```typescript
// apps/web-frontend/src/services/sse.ts
export class SSEClient {
  private eventSource: EventSource | null = null;
  private listeners: Map<string, Set<(data: any) => void>> = new Map();

  connect(url: string) {
    const token = localStorage.getItem('access_token');
    const urlWithAuth = `${url}?token=${token}`;

    this.eventSource = new EventSource(urlWithAuth);

    this.eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.emit(data.type, data);
    };

    this.eventSource.onerror = (error) => {
      console.error('SSE error:', error);
      this.reconnect(url);
    };
  }

  on(type: string, callback: (data: any) => void) {
    if (!this.listeners.has(type)) {
      this.listeners.set(type, new Set());
    }
    this.listeners.get(type)!.add(callback);
  }

  off(type: string, callback: (data: any) => void) {
    this.listeners.get(type)?.delete(callback);
  }

  private emit(type: string, data: any) {
    this.listeners.get(type)?.forEach((callback) => callback(data));
  }

  private reconnect(url: string) {
    setTimeout(() => {
      this.connect(url);
    }, 5000);
  }

  disconnect() {
    this.eventSource?.close();
    this.eventSource = null;
    this.listeners.clear();
  }
}

// React hook
import { useEffect, useState } from 'react';

export function useNotifications() {
  const [notifications, setNotifications] = useState<any[]>([]);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    const client = new SSEClient();

    client.on('connected', () => setConnected(true));
    client.on('notification', (data) => {
      setNotifications((prev) => [...prev, data]);
    });

    client.connect(`${process.env.NEXT_PUBLIC_API_URL}/notifications/stream`);

    return () => {
      client.disconnect();
    };
  }, []);

  return { notifications, connected };
}
```

---

## Migration Patterns

### 1. Strangler Fig Pattern

#### Phase 1: Setup (Weeks 1-2)

```
┌─────────────────┐
│  Load Balancer  │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
┌───▼──┐  ┌──▼────┐
│ Old  │  │ Motia │
│ API  │  │  API  │
└──────┘  └───────┘
  100%        0%
```

**Actions:**
1. Deploy Motia alongside existing API
2. Implement health checks and monitoring
3. Test Motia in staging environment
4. No production traffic yet

#### Phase 2: Pilot (Weeks 3-6)

```
┌─────────────────┐
│  Load Balancer  │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
┌───▼──┐  ┌──▼────┐
│ Old  │  │ Motia │
│ API  │  │  API  │
└──────┘  └───────┘
   90%       10%
```

**Actions:**
1. Route 10% of traffic to Motia
2. Implement new features in Motia
3. Migrate non-critical endpoints
4. Monitor performance and errors

#### Phase 3: Migration (Weeks 7-16)

```
┌─────────────────┐
│  Load Balancer  │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
┌───▼──┐  ┌──▼────┐
│ Old  │  │ Motia │
│ API  │  │  API  │
└──────┘  └───────┘
   50%       50%
```

**Actions:**
1. Incrementally migrate endpoints
2. Gradually increase traffic to Motia
3. Maintain feature parity
4. Continuous monitoring

#### Phase 4: Completion (Weeks 17-20)

```
┌─────────────────┐
│  Load Balancer  │
└────────┬────────┘
         │
         │
      ┌──▼────┐
      │ Motia │
      │  API  │
      └───────┘
         100%
```

**Actions:**
1. Route all traffic to Motia
2. Decommission old API
3. Optimize Motia deployment
4. Document and celebrate

### 2. Feature Flag Pattern

```typescript
// libs/shared/feature-flags/src/lib/flags.ts
export const featureFlags = {
  USE_MOTIA_AUTH: process.env.FEATURE_USE_MOTIA_AUTH === 'true',
  USE_MOTIA_ORDERS: process.env.FEATURE_USE_MOTIA_ORDERS === 'true',
  USE_MOTIA_PAYMENTS: process.env.FEATURE_USE_MOTIA_PAYMENTS === 'true',
  USE_MOTIA_NOTIFICATIONS: process.env.FEATURE_USE_MOTIA_NOTIFICATIONS === 'true'
};

// apps/legacy-api/src/routes/orders.ts
import { featureFlags } from '@workspace/shared/feature-flags';
import { createOrder as legacyCreateOrder } from '../services/orders';
import { apiClient } from '@workspace/api-contracts';

export async function createOrder(req: Request, res: Response) {
  if (featureFlags.USE_MOTIA_ORDERS) {
    // Route to Motia
    const result = await apiClient.createOrder(req.body.items);
    return res.json(result);
  } else {
    // Use legacy implementation
    const result = await legacyCreateOrder(req.body.items);
    return res.json(result);
  }
}
```

---

## References

1. **Motia Official Resources**
   - Documentation: https://motia.dev/docs
   - GitHub: https://github.com/MotiaDev/motia
   - Examples: https://github.com/MotiaDev/motia-examples

2. **NX Documentation**
   - NX Monorepo: https://nx.dev/
   - Custom Generators: https://nx.dev/extending-nx/recipes/local-generators

3. **Integration Patterns**
   - Strangler Fig: https://martinfowler.com/bliki/StranglerFigApplication.html
   - Microservices Patterns: https://microservices.io/patterns/

4. **Third-Party Services**
   - Prisma: https://www.prisma.io/docs
   - Redis: https://redis.io/docs
   - Auth0: https://auth0.com/docs
   - Stripe: https://stripe.com/docs

---

*Document Version: 1.0*
*Last Updated: 2025-09-30*
*Prepared for: BuzzTrail Extension Project*