ClearVibeArchitecture (CVA) — Complete Guide

2025-10-16

Table of Contents

  1. Introduction and TL;DR
  2. Glossary and Terminology
  3. Architecture Map and Layers
  4. Principles and Rules
  5. Patterns
  6. Data Schema and Contracts
  7. Observability
  8. Security
  9. DevEx and Productivity
  10. Reference Skeleton (Go)
  11. Reference Skeleton (Symfony/PHP)
  12. Evolution Policies
  13. Feature Toggles
  14. Visualization
  15. Implementation Checklists
  16. Licensing and Contribution

Part 1: Introduction and TL;DR

1.1 What is ClearVibeArchitecture (CVA)

ClearVibeArchitecture (CVA) is an architectural style for backend systems that combines:

  • Hexagonal (Ports & Adapters) as the foundation for domain isolation
  • Events by default (Domain Events + Outbox/Inbox, idempotency)
  • Observability by default (traces, metrics, structured logs, timeline)
  • Mandatory Feature Toggles as a cross-cutting pattern for all new features
  • Flow visualization (web/VR) as a product artifact, not a “nice option”

In short: hexagonal architecture “with batteries included” — transparent, observable, and evolutionarily manageable.

1.2 Problems It Solves

  1. Hard to safely change the system → feature flags + canary/blue-green
  2. Can’t see “what’s happening inside” → otel-tracing + business metrics + timeline
  3. Reliable integration between services → Outbox/Inbox + idempotency
  4. Developers drowning in infrastructure → clean domain and contracts at boundaries
  5. Hard to explain system behavior to business → request/event flow visualizer

1.3 Design Goals

  • Transparency: every request and event is traced through all layers
  • Domain isolation: domain model is independent of infrastructure
  • Reliable delivery: events are published transactionally (Outbox)
  • Managed evolution: all new branches behind feature flags with contract versioning
  • Developer Experience: module templates, unified CI/CD practices, tests as standard

1.4 Non-Functional Requirements (NFR)

  • Reliability: idempotent handlers, retries, deduplication
  • Observability: p95-latency, error rate, saturation as mandatory metrics
  • Security: Zero-Trust boundaries; message signing; audit of flag/contract changes
  • Performance: in-proc cache for flag decisions, back-pressure, I/O batching
  • Compatibility: SemVer for API/event contracts, n-1 support

1.5 TL;DR Principles

  • Domain First: domain doesn’t know about ORM/HTTP/broker
  • Ports & Adapters: all I/O through interfaces (in/out-ports)
  • Events First: domain events are first-class; publishing via Outbox
  • Observability First: trace_id everywhere; business metrics on domain events
  • Feature-Toggles Everywhere: new functionality doesn’t live without a flag and kill-switch
  • Contracts First: API/event schemas are versioned, verifiable, compatible
  • Visualize the Flow: mandatory visualization of request/event path

1.6 Scope of Application

  • Microservices and large monoliths with decomposition prospects
  • High integration load, frequent releases, A/B experiments
  • Teams for whom transparency and incident reproducibility are important

Not the best choice if the system is extremely simple, rarely changes, and doesn’t require telemetry/events.

1.7 “CVA Readiness” Criteria

  • All new features behind feature flags with canary and kill-switch
  • Outbox/Inbox and idempotent handlers present
  • OpenTelemetry (tracing), structured logs, and key business metrics enabled
  • API/event contracts described with schemas, CI-validated, SemVer maintained
  • Web/VR flow visualizer available (minimum — web graph + timeline)
  • Module templates/generators, linters, PR checklists, basic e2e tests

1.8 Output Artifacts

  • Architecture map of layers and ports (in/out), domain model and context boundaries
  • Contract catalog (OpenAPI/Proto/JSON-Schema/Avro) with SemVer and checks
  • Outbox/Inbox library/module, FeatureGate SDK, otel-integration
  • SLO dashboards and flow visualizer (minimum — web)
  • Code templates (Go, Symfony/PHP), Makefile/Compose, CI-pipeline

Part 2: Glossary and Terminology

2.1 Basic Entities

  • Domain — business area describing business rules and invariants
  • Aggregate — root entity encapsulating state and behavior of related objects
  • Event (Domain Event) — immutable fact recorded in the domain
  • Command — intention to change state (create, update, delete)
  • Query — intention to get data without side effects
  • Use Case — application logic linking command/query and domain

2.2 Ports and Adapters

  • InPort — system entry interface (API, UI, CLI, test)
  • OutPort — system exit interface (database, message broker, external APIs)
  • Adapter — port implementation for specific infrastructure

2.3 Event Components

  • Outbox — table/storage for reliable event publishing with transaction
  • Inbox — table/storage for receiving and deduplicating incoming events
  • Saga/Process Manager — coordinates long-running processes through event sequence

2.4 Observability

  • Trace ID — unique request identifier, passed through all layers
  • Span — part of trace reflecting a step (e.g., SQL query, API call)
  • Metric — measurement (latency, error rate, business metric)
  • Structured Log — log in JSON format with mandatory fields (timestamp, trace_id, level, message)

2.5 Feature Toggles

  • Feature Flag — binary switch or variant parameter controlling feature availability
  • Variant — value of variant flag (A/B/n-test)
  • Kill-Switch — flag for instant disabling of problematic feature
  • Exposure Event — event of feature being shown to user

2.6 Contracts

  • API Contract — formal API description (OpenAPI, gRPC proto)
  • Event Contract — event structure description (JSON Schema, Avro)
  • Backward Compatibility — new description doesn’t break previous version clients
  • SemVer — contract versioning following Semantic Versioning rules

Part 3: Architecture Map and Layers

3.1 General Schema

┌─────────────────────────────────────────────────────┐
│           Interface Layer                           │
│   (REST, gRPC, GraphQL, CLI, VR/AR)                 │
└────────────────┬────────────────────────────────────┘
                 │ InPorts
┌────────────────▼────────────────────────────────────┐
│           Application Layer                         │
│   (Commands, Queries, Handlers, Policies)           │
└────────────────┬────────────────────────────────────┘
                 │ Domain Services
┌────────────────▼────────────────────────────────────┐
│           Domain Layer                              │
│   (Entities, Aggregates, Events, Value Objects)     │
└─────────────────────────────────────────────────────┘
                 ▲
                 │ OutPorts
┌────────────────┴────────────────────────────────────┐
│           Infrastructure Layer                      │
│   (DB, Brokers, Outbox/Inbox, Observability)        │
└─────────────────────────────────────────────────────┘

3.2 Interface Layer

  • Entry: REST, gRPC, GraphQL, CLI, VR/AR-visualizer
  • Tasks: accept commands/queries, convert to DTO, pass to Application
  • Features: logging, tracing, authN/authZ

3.3 Application Layer

  • Heart of application logic: commands, queries, handlers, policies
  • Coordination: orchestrators, saga, process managers
  • Validation and DTO mapping
  • Transaction boundaries guarantee: one use case = one transaction
  • All side effects through Outbox

3.4 Domain Layer

  • Entities, Aggregates, Value Objects
  • Invariants, business rules, ubiquitous language
  • Domain Events as first-class objects
  • Domain Services — pure functions without infrastructure
  • Domain doesn’t know about ORM, HTTP, brokers

3.5 Infrastructure Layer

  • Port implementations: repositories, broker adapters, external API clients
  • Outbox/Inbox — mandatory components for publishing/receiving events
  • Observability stack: otel-integration, logging, metrics
  • Caching, file storage, integrations with external services

Part 4: Principles and Rules

4.1 Clean Core (Domain First)

  • Domain is isolated from infrastructure
  • Forbidden to use ORM annotations, SQL, or external service SDKs inside domain
  • Invariants are checked only in domain

4.2 Ports and Adapters

  • All external interactions through interfaces (Ports)
  • Interface implementations only in Infrastructure (Adapters)
  • Application calls OutPorts, Domain knows nothing about them

4.3 Events by Default

  • Every significant change is recorded as Domain Event
  • Events are published through Outbox with transaction
  • Inbox with idempotency used for incoming events

4.4 Transaction Boundaries

  • One use case = one transaction
  • Side effects (sending to broker, integrations) are recorded in Outbox
  • Outbox processing is asynchronous and retriable

4.5 Observability by Default

  • Every request and event accompanied by trace_id
  • All handlers and adapters must log and metric their work
  • Business events become part of metrics (e.g., order.created.count)

4.6 Contracts at Boundaries

  • API and events described by contracts (OpenAPI/Proto/Avro/JSON Schema)
  • Contracts are versioned (SemVer)
  • Backward Compatibility is mandatory (n-1 version support)

4.7 Feature Toggles Everywhere

  • Any new functionality implemented only behind a flag
  • Feature flag is mandatory even if functionality will always be enabled later
  • Each flag has an owner, sunset date, and kill-switch

4.8 Flow Visualization

  • Request and event timeline must be reproducible in visualizer (web/VR)
  • Bottlenecks are automatically highlighted (heatmap)
  • Visualization is part of the product, not an “additional tool”

Part 5: Patterns

5.1 Hexagonal / Ports & Adapters

  • Basic architecture pattern
  • Domain is isolated, input/output dependencies as InPorts/OutPorts
  • External world interaction through adapters

5.2 CQRS (optional)

  • Separation of commands (state changes) and queries (data reading)
  • Used where reading differs significantly from writing
  • Allows scaling reads and writing optimized projections

5.3 Outbox / Inbox

  • Outbox: transactional event recording with DB change
  • Inbox: registration and deduplication of incoming messages
  • Guarantees “exactly-once delivery” at application level

5.4 Saga / Process Manager

  • Long-running process management
  • Saga: chain of steps with compensations
  • Process Manager: reacts to events, coordinates actions of multiple aggregates/services

5.5 Feature Toggles (mandatory)

  • Cross-cutting pattern: any new functionality implemented behind flag
  • Flags have owner, sunset dates, kill-switch
  • Percentage rollout, user segments, A/B/n-tests supported
  • Every exposure event (fact of flag usage) is logged

5.6 Observability Patterns

  • Distributed Tracing: trace_id through all layers
  • Structured Logging: JSON logs with key fields
  • Metrics & SLOs: business and technical metrics; auto-alerts
  • Timeline Visualization: event and request flow displayed in web/VR

5.7 Deployment Patterns

  • Feature Flags + Canary Release: new functionality enabled gradually
  • Blue/Green Deployment: two parallel environments, fast switching
  • Rollback by metrics: automatic feature/version disabling on degradation

Part 6: Data Schema and Contracts

6.1 API Contracts

  • All public APIs described in OpenAPI or gRPC Proto
  • Contracts pass automatic CI validation
  • Strict versioning: SemVer (1.2.3)
  • Backward compatibility: n-1 client version support
  • Contracts published to artifact repository

6.2 Event Contracts

  • Events described in JSON Schema, Avro, or Protobuf
  • Each event has: event_name, version, timestamp, trace_id, payload
  • Mandatory fields: id, trace_id, source
  • Events pass schema validation before publishing

6.3 Versioning

  • Contracts versioned independently of services
  • Multiple event versions support: consumers can read v1 and v2 in parallel
  • During transition: producer starts publishing both formats (dual write)

6.4 Database Schemas

  • Migrations managed by tools: Liquibase/Flyway/golang-migrate/DoctrineMigrations
  • Every DB change accompanied by migration script
  • Shadow-write/read supported for complex schema changes
  • All migrations pass through CI and test database

Part 7: Observability

7.1 “Observability by Default” Principle

  • Any new service or module in CVA must have built-in observability tools
  • Metrics, logs, and traces aren’t added “later” — they’re part of architecture
  • Observability covers both technical and business processes

7.2 Traces (Distributed Tracing)

  • OpenTelemetry or compatible standard used
  • Each request has unique trace_id
  • Each operation (SQL, RPC, external API) recorded as span
  • All events (Domain Events) also carry trace_id
  • Visualizer (web/VR) builds timeline based on trace_id

7.3 Logs (Structured Logging)

  • Format: JSON
  • Mandatory fields: timestamp, level, trace_id, service, message
  • Logs written to stdout → centralized storage (ELK, Loki)
  • Errors and business events recorded equally structured

7.4 Metrics

  • Technical: latency (p95/p99), error_rate, saturation, throughput
  • Business: order count, conversion, rule rejection count
  • Feature Flags: exposure metrics (how many users see feature), enable_rate
  • Metrics available in Prometheus/Grafana or equivalents

7.5 Alerts and SLO

  • Every critical metric has SLO (Service Level Objective)
  • Violations → alerts (PagerDuty, Slack, Email)
  • Alerts must be actionable (clear what to do when triggered)
  • Feature flags have auto-rollback by SLO

Part 8: Security

8.1 Zero Trust Principle

  • Each service and component interacts with others only through verified channels
  • No trust by default even within same network
  • Authorization and authentication applied at every level

8.2 Authentication (AuthN)

  • External calls: OAuth2 / OpenID Connect / mTLS
  • Internal calls: service accounts + mTLS
  • All requests must contain correlation trace_id and authorization token

8.3 Authorization (AuthZ)

  • RBAC (Role-Based Access Control) or ABAC (Attribute-Based Access Control)
  • Permission checks performed in Application Layer (policies)
  • Feature Flags can be limited by roles/segments

8.4 Encryption

  • In transit: TLS 1.3 (API, brokers, DB)
  • At rest: disk/table/object encryption (AES-256)
  • Confidential data (PII) always encrypted

8.5 Secrets Management

  • Secrets not stored in code or environment variables
  • Vault/KMS used (HashiCorp Vault, AWS KMS, GCP Secret Manager)
  • Secrets access strictly by principle of least privilege

Part 9: DevEx and Productivity

9.1 DevEx-first Principle

  • Architecture should be convenient for developers
  • Templates, tools, and processes built into CVA
  • Developers spend minimum time on routine and infrastructure

9.2 Scaffolds and Generators

  • Code generators for entities, commands, events, ports, and adapters
  • make scaffold module=Order → creates structure:
    • Domain: entity, events, value objects
    • Application: commands, handlers, policies
    • Infrastructure: repository, adapters
  • Uniformity guarantee across projects

9.3 Code Style and Linters

  • Unified code style (Go, PHP, JS/TS)
  • Pre-commit hooks: linters, tests, security scans
  • Mandatory trace_id, logs, feature flags checking

9.4 CI/CD Pipeline

CI checks:

  • compilation/build
  • tests (unit, integration, e2e)
  • contract schemas (API, events)
  • DB migrations
  • security scan

CD supports blue/green and canary deployment


Part 10: Reference Skeleton (Go)

10.1 Project Structure

/clearvibe
  /cmd/app/main.go
  /internal
    /domain/order
      entity.go, events.go, service.go
    /app/order
      commands.go, handler.go, policies.go, ports.go
    /infra
      /db: order_repo_pg.go
      /broker: outbox.go, inbox.go
      /http: server.go
      /obs: tracing.go, metrics.go, logging.go
      /flags: feature_gate.go

10.2 Port Interfaces

1
2
3
4
5
6
7
8
type OrderRepo interface {
    Save(*Order) error
    FindByID(id string) (*Order, error)
}

type FeatureGate interface {
    Enabled(ctx FeatureContext, key string) bool
}

10.3 Command and Handler

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type CreateOrderCmd struct {
    CustomerID string
    Items      []Item
}

func (h *createOrderHandler) Handle(cmd CreateOrderCmd) (string, error) {
    if h.flags.Enabled(FeatureContext{UserID: cmd.CustomerID}, "orders.dynamic_pricing") {
        // new logic branch
    }
    ord, _ := domain.NewOrder(cmd.CustomerID, cmd.Items)
    h.repo.Save(ord)
    h.outbox.Add("order.created", ord.ID, OrderCreated{ID: ord.ID})
    return ord.ID, nil
}

Part 11: Reference Skeleton (Symfony/PHP)

11.1 Project Structure

src/
  Domain/Order/
    Entity/Order.php
    Event/OrderCreated.php
  Application/Order/
    Command/CreateOrder.php
    Handler/CreateOrderHandler.php
  Infrastructure/
    Persistence/Doctrine/OrderRepository.php
    Messaging/OutboxPublisher.php
    FeatureFlags/RedisFeatureGate.php

11.2 Entity and Event

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
final class Order {
    private string $id;
    private string $customerId;
    private float $total;

    public static function create(string $customerId, array $items): self {
        return new self($customerId, $items);
    }
}

final class OrderCreated {
    public function __construct(
        public readonly string $id,
        public readonly float $total,
    ) {}
}

Part 12: Evolution Policies

12.1 General Principle

Evolution is managed and observable. Any change goes through feature flags, contracts, and migrations, has owner, risk plan, and rollback paths.

12.2 Contract Versioning (API/Events)

  • SemVer: MAJOR.MINOR.PATCH
  • n-1 compatibility: at least one previous version supported
  • Dual write/read: during event migration, producer publishes vN and vN+1
  • CI compatibility validators: forbid breaking-changes without MAJOR

12.3 Feature Lifecycle

  1. Draft: flag created (disabled), owner, goal, success metrics, sunset date
  2. Internal: enabled for dev/stage/own team
  3. Canary: 1% → 5% → 25% → 50% → 100% (deterministic bucketing)
  4. General Availability: flag default on
  5. Sunset: flag and dead code removed, contracts stabilized

12.4 Release Strategies

  • Blue/Green: two environments, traffic switching
  • Canary: incremental rollout with auto-guards by SLO
  • Dark Launch: code deployed, feature disabled by flag until activation

Part 13: Feature Toggles

13.1 Principle

Feature Toggles are mandatory and cross-cutting pattern in CVA. Any new functionality implemented only behind a flag.

13.2 Flag Types

  • Boolean: on/off
  • Percentage: traffic percentage (canary rollout)
  • Segment: enabling by attributes (country, tier, role)
  • Multivariant: multiple variants for A/B/n-tests

13.3 Storage

  • Storage: Postgres (source of truth) + Redis (cache, pub/sub)
  • Schema: flags(id, key, type, rules, default, owner, version, ttl, updated_at)
  • Versioning: SemVer for flag contracts, n-1 support

13.4 Metrics and Observability

  • Exposure events: flag.exposed, flag.variant
  • Metrics: exposure_count, enable_rate, error_rate
  • Dashboards: variant comparison (A/B), correlation with business metrics
  • Trace_id: always passed in exposure events

Part 14: Visualization

14.1 Principle

In CVA, visualization is not a “nice option” but a mandatory layer. The system must show data and event flow.

14.2 Timeline

  • Displays request steps chronologically
  • Examples: HTTP request accepted, Handler executed, Event recorded in Outbox
  • Each step corresponds to span (trace)
  • Timeline available in web interface and exported to VR

14.3 Flow Graph

  • Nodes: services, aggregates, adapters
  • Edges: calls and events
  • Filter support: by trace_id, event type, errors/latency

14.4 Heatmap

  • Bottleneck highlighting
  • Latency/error_rate metrics visualized in color
  • Red = problem, green = normal

14.5 VR Visualization

  • Data flow can be “seen” in 3D (VR/AR)
  • Service nodes in space, event lines moving in real-time
  • Useful for onboarding new team members and incident analysis

Part 15: Implementation Checklists

15.1 General Project Checklist

  • Bounded Contexts and Ubiquitous Language defined
  • Architecture map of layers formed
  • Architecture owner appointed

15.2 Domain Layer

  • All entities described as Entity/ValueObject
  • Invariants fixed and test-covered
  • Domain Events defined and documented
  • No dependencies on ORM/HTTP/brokers

15.3 Application Layer

  • Each action formed as Command/Query
  • Handler for each command
  • Policies validate access and rules
  • Transaction boundaries defined
  • Feature Flags integrated into use cases

15.4 Infrastructure Layer

  • Repositories implemented via OutPorts
  • Outbox connected (mandatory)
  • Inbox connected for incoming events
  • Adapters configured for API/brokers/DB
  • Observability components connected

15.5 Feature Toggles

  • Every new code has feature flag
  • Flags have owner, sunset dates, kill-switch
  • Exposure events logged
  • Rollout scenarios documented
  • Tests include on/off scenarios

15.6 Observability

  • All requests/events have trace_id
  • Logs structured (JSON)
  • Metrics: technical + business
  • Dashboards and alerts configured
  • Visualizer connected (timeline/flow graph/VR)

Part 16: Licensing and Contribution

16.1 License

  • Open Source (MIT/Apache 2.0): architectural principles, checklists, and templates freely available
  • Can be used in commercial and non-commercial projects without restrictions
  • Only requirement — maintain authorship and license mention

16.2 Contribution Guide

Pull Request accepted only if:

  • ADR written for changes
  • CI passed (contracts, tests, migrations)
  • Checklists and documentation updated
  • Examples added (Go/PHP SDK, migrations, metrics)

16.3 Governance

  • Maintainers: responsible for review and releasing new CVA manifest versions
  • Contributors: contribute ideas, bugfixes, additions to checklists and patterns
  • Decisions made through RFC/ADR

Key Differences of CVA

From Classical Hexagonal/Clean Architecture

Same foundation (DDD + Hexagonal), but CVA makes mandatory things usually “added later”:

  • Events (Domain Events + Outbox/Inbox)
  • Observability (tracing/metrics/structured logs)
  • Feature flags with cross-cutting integration
  • Managed evolution (canary/blue-green, contract versioning)
  • Flow visualization (web/VR)

Idea: system is initially “live, transparent, and safely evolving”.

Where CVA is Better

  1. Transparency and debugging — built-in OpenTelemetry, business metrics, timeline
  2. Reliable integration — Outbox/Inbox, idempotency, retries by default
  3. Safe releases — feature flags, canary rollout, kill-switch, auto-rollback
  4. Managed evolution — SemVer, dual write/read, shadow write/read
  5. Developer Experience — templates, checklists, standards
  6. Business understanding — flow visualization, business metrics out of the box
  7. Security by default — RBAC, audit, zero-trust

When to Choose CVA

  • Microservices and integration-heavy systems
  • Frequent releases and experiments (growth/product teams)
  • High requirements for event delivery reliability
  • Need to “transparently” explain technology to business
  • Team and project scaling planned

When to Stay with Classical Hexagonal

  • Simple service/monolith without active evolution
  • Small team, no resources for telemetry and feature flags
  • Almost no external integrations, soft SLA

Conclusion

ClearVibeArchitecture is not just a set of patterns, but a holistic approach to building modern backend systems.

CVA makes the system:

  • Transparent — every request visible from start to finish
  • Reliable — events delivered with guarantees
  • Safe — changes controlled and rollback-able
  • Understandable — visualization helps everyone: from developers to business

This is “Hexagonal on steroids” — more expensive at start, but pays off many times on medium and large systems.