> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lerian.studio/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> Explore Matcher's modular monolith built on DDD, hexagonal architecture, and CQRS, with seven bounded contexts that evolve independently.

Matcher is a **modular monolith** with Domain-Driven Design (DDD) and hexagonal architecture. CQRS separates commands (writes) from queries (reads).

This keeps operations simple while maintaining clear boundaries. Each module can evolve independently without the complexity of microservices.

## Architecture overview

***

<Frame caption="Matcher architecture overview">
  <img src="https://mintcdn.com/lerian-49cb71fc/Gw2zNPznAbAjotN1/images/en/d2/matcher-architecture.svg?fit=max&auto=format&n=Gw2zNPznAbAjotN1&q=85&s=1929acad7a31c0d90866e9387fb605fd" alt="Matcher Architecture" width="1076" height="1449" data-path="images/en/d2/matcher-architecture.svg" />
</Frame>

## Bounded contexts

***

Matcher has seven modules. Each owns its data and exposes clean interfaces to the others.

* **Configuration**: What you're reconciling (contexts, sources, field maps, rules)
* **Discovery**: External data source connections, schema detection, and extraction orchestration with Matcher's embedded extraction engine
* **Ingestion**: Getting data in (parsing, validation, normalization)
* **Matching**: The engine (rule execution, confidence scoring)
* **Exception**: Handling unmatched items (workflow, routing, resolution)
* **Governance**: Audit trails (immutable logs for compliance)
* **Reporting**: Visibility (reports, exports, dashboards)

### Configuration

Defines **what** you're reconciling and **how**.

**Handles:**

* Contexts (what you reconcile)
* Sources (where data comes from)
* Field maps (translating external fields)
* Rules (how to match)

**Key models:**

* `ReconciliationContext`: The reconciliation scope
* `ReconciliationSource`: Source configuration
* `FieldMap`: Field translation rules
* `MatchRule`: Matching logic

### Discovery

The Discovery bounded context manages external data source connectivity, schema detection, and extraction orchestration with the extraction engine. Discovery runs inside Matcher. There is no separate extraction service to deploy.

**Responsibilities:**

* Manage external data source connections
* Detect and cache source schemas
* Run in-process extractions and hand results directly to Ingestion
* Track connection and extraction lifecycles

**Key entities:**

* `FetcherConnection`: External source connection managed locally by the extraction engine
* `ExtractionRequest`: Tracks an extraction lifecycle run by the embedded engine

<Info>
  See [Discovery](/en/products/matcher/integrations/matcher-discovery) for how Discovery connects to external databases with the extraction engine.
</Info>

### Ingestion

The Ingestion bounded context handles data intake and normalization.

**Responsibilities:**

* Parse uploaded files (CSV, JSON, XML)
* Validate incoming data against configured schemas
* Normalize external data into a canonical representation
* Detect and handle duplicate records
* Emit domain events when ingestion completes

**Key entities:**

* `IngestionJob`: Tracks ingestion lifecycle and status
* `Transaction`: Normalized canonical transaction record

**Events published:**

* `ingestion.completed`: Indicates data readiness for matching

### Matching

The Matching bounded context contains the reconciliation engine.

**Responsibilities:**

* Load applicable rules for a reconciliation context
* Execute matching strategies (exact, tolerance, fuzzy, date-based)
* Calculate confidence scores
* Create match groups and allocate transactions
* Identify unmatched transactions

**Key entities:**

* `MatchRun`: Execution of a matching job
* `MatchGroup`: Group of reconciled transactions
* `MatchItem`: Individual transaction allocation

**Events published:**

* `match_group.confirmed`: A match group has been finalized
* `match_group.unmatched`: A previously confirmed match was reverted
* `transaction.pending_review`: A non-automatic candidate needs review

### Exception management

The Exception bounded context manages unresolved transactions.

**Responsibilities:**

* Classify exceptions by severity
* Route exceptions to internal teams or external systems
* Support manual overrides and adjustments
* Track resolution status and SLAs
* Integrate with external workflow tools

**Key entities:**

* `Exception`: An unresolved transaction
* `Resolution`: Outcome of exception handling
* `RoutingRule`: Routing and escalation logic

**Integrations:**

* JIRA for issue tracking
* ServiceNow for Table API incidents
* Webhooks for custom workflows

The ServiceNow connector creates Table API incidents after you configure it. It uses one create attempt because a retried request could create a duplicate incident.

### Governance

The Governance bounded context preserves reconciliation traceability.

**Responsibilities:**

* Record instrumented auditable mutation workflows in immutable audit logs
* Provide queryable audit history
* Support regulatory and compliance reporting

**Key entities:**

* `AuditLog`: Append-only record of instrumented auditable mutation workflows

<Warning>
  Audit logs are append-only by design. Nobody can modify or remove entries. This design preserves compliance integrity.
</Warning>

### Reporting

The Reporting bounded context provides operational visibility.

**Responsibilities:**

* Generate reconciliation reports
* Expose dashboard metrics
* Export reconciliation data in multiple formats

**Key entities:**

* `Report`: Reconciliation summary
* `Dashboard`: Aggregated operational metrics
* `ExportJob`: Asynchronous export execution

## Data flow

***

Reconciliation follows a deterministic pipeline across bounded contexts:

<Steps>
  <Step title="Configuration">
    You define reconciliation contexts, sources, field mappings, and rules through the API.
  </Step>

  <Step title="Discovery">
    Discovery connects to external sources, detects their schemas, and runs extractions in-process with the extraction engine. Discovery hands extracted results directly to Ingestion.
  </Step>

  <Step title="Ingestion">
    Ingestion parses, validates, normalizes, and deduplicates uploaded files and the data that Discovery extracts. Ingestion emits an `ingestion.completed` event.
  </Step>

  <Step title="Matching">
    Matching applies rules to eligible transactions and produces match groups with confidence scores on an integer scale of 0 to 100. EXACT and TOLERANCE groups with a confidence of at least 90 out of 100 can auto-confirm. FUZZY and DATE\_LAG groups always require manual review. Unmatched items become exceptions.
  </Step>

  <Step title="Exception handling">
    The Exception context classifies and routes exceptions. Resolution happens manually or through external systems. Resolution updates return to Matcher.
  </Step>

  <Step title="Governance">
    Governance records instrumented auditable mutation workflows across the pipeline in immutable audit logs.
  </Step>

  <Step title="Reporting">
    Users access reports and dashboards showing reconciliation status, match rates, and exception aging.
  </Step>
</Steps>

## Infrastructure components

***

Matcher relies on the following infrastructure services:

| Component                     | Purpose                    | Usage                                                                           |
| ----------------------------- | -------------------------- | ------------------------------------------------------------------------------- |
| **PostgreSQL**                | Primary data store         | Domain data; configured multi-tenant deployments resolve a pool for each tenant |
| **Valkey (Redis-compatible)** | Cache and coordination     | Deduplication, locks, idempotency keys                                          |
| **Streaming backbone**        | Business-event publication | Domain events published via lib-streaming                                       |
| **RabbitMQ**                  | Infrastructure queues      | Internal work queues and dead-letter handling                                   |
| **Systemplane**               | Runtime configuration      | Hot-reload settings without restart via `/system/matcher/:key` admin API        |

### Database architecture

* **Tenant-specific pool resolution** in configured multi-tenant deployments for data separation
* **Strong consistency** for matching and exception state
* **Eventual consistency** for reporting views

### Multi-tenancy

Matcher enforces strict tenant isolation:

* In multi-tenant deployments with `AUTH_PROVIDER=plugin-auth`, Matcher takes tenant identity from `tenant_id` or `tenantId` JWT claims
* Single-tenant and authentication-disabled deployments use the configured default tenant
* Matcher never accepts tenant identifiers from request parameters
* All database access goes through the active tenant's connection pool
* Matcher automatically constrains every query to the active tenant

<Info>
  This model prevents cross-tenant data access and supports regulatory and audit requirements.
</Info>

## Design patterns

***

### Hexagonal architecture

Each bounded context follows the ports-and-adapters pattern:

```
context/
├── adapters/
│ ├── http/
│ ├── postgres/
│ └── redis/
├── ports/
├── services/
│ ├── command/
│ ├── query/
│ └── worker/
└── domain/
 ├── entities/
 └── errors/
```

### Cqrs-light

Matcher separates write and read paths at the service level:

* `*_commands.go` for state mutations
* `*_queries.go` for read operations

This improves code organization and allows independent optimization of query paths.

### Outbox pattern

Matcher uses per-event delivery policies. Matcher persists an outbox record for outbox-backed events and dispatches them asynchronously. Other events can use direct delivery with an outbox fallback when the circuit is open.

## Next steps

***

<Card title="Quick start" icon="rocket" href="/en/products/matcher/getting-started/matcher-quick-start" horizontal>
  Explore the architecture through a guided example.
</Card>

<Card title="Security" icon="shield-halved" href="/en/products/matcher/reference/matcher-security" horizontal>
  Review authentication, authorization, and tenant isolation mechanisms.
</Card>
