# LotusCloud Event-Driven Architecture

## Overview

LotusCloud uses event-driven architecture for async service communication,
following patterns used by hyperscaler control planes.

## Event Bus

**Technology**: RabbitMQ (current), Kafka (future scale)

```
Service A → publish event → RabbitMQ → consume → Service B
                                      → consume → Service C
```

## Event Topics

| Topic | Publisher | Consumers |
|-------|----------|-----------|
| resource.created | All services | billing, audit, quota |
| resource.deleted | All services | billing, audit, quota |
| resource.updated | All services | audit, notification |
| vm.started | compute-service | billing, monitor |
| vm.stopped | compute-service | billing, monitor |
| cluster.created | container-service | billing, audit |
| database.created | postgres/mysql/mongo | billing, audit |
| backup.completed | backup-service | notification, audit |
| billing.usage | billing-service | costmgmt, notification |
| security.alert | ddos/waf/firewall | notification, audit |
| migration.progress | migration-service | notification |

## Event Format

```json
{
  "id": "evt-uuid",
  "type": "vm.created",
  "source": "compute-service",
  "project_id": "proj-uuid",
  "resource_id": "vm-uuid",
  "timestamp": "2026-03-09T10:00:00Z",
  "data": {
    "name": "web-server",
    "cpu": 4,
    "ram": 8
  }
}
```

## Billing Usage Publisher

All services use the shared `events.BillingUsagePublisher`:

```go
pub := events.NewBillingUsagePublisher(rabbitMQURL, "service-name")
// Publishes usage events for billing metering
```

## Event Flow: VM Creation

```
User request → API Gateway
  → compute-service creates VM
  → publish "vm.created" event
  → billing-service starts metering
  → audit-service logs activity
  → monitor-service tracks health
  → notification-service alerts user
```

## Async Provisioning (Workflow Engine)

Complex operations use workflow-engine (port 8111):

```
Create K8s Cluster request
  → workflow-engine orchestrates:
    1. Allocate network (network-service)
    2. Provision nodes (compute-service)
    3. Bootstrap control plane
    4. Install CNI + ingress
    5. Register cluster (container-service)
    6. Update status + notify
```

## Future: Kafka Migration

At scale (>1000 events/sec), migrate from RabbitMQ to Kafka:

- Kafka provides durable event log
- Enables event replay for debugging
- Supports stream processing (analytics)
