> For the complete documentation index, see [llms.txt](https://host2host.onibonje.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://host2host.onibonje.com/docs/13-design-patterns.md).

# Design Patterns Reference

## 1. Overview

This document catalogs the **design patterns** used across the Heirs H2H Integration Platform. Patterns are grouped by category and mapped to **Maven modules**, **classes/components**, and **documentation** so implementers know where each pattern lives in code.

The platform combines:

* **Classic OOP patterns** (Adapter, Facade, Strategy, Registry)
* **Enterprise Integration Patterns (EIP)** via Apache Camel
* **Architecture patterns** (layered, control/data plane, event-driven)
* **Configuration patterns** (externalized config, cache-aside, publish workflow)

```mermaid
flowchart TB
  subgraph code [Capabilities in JARs]
    Adapter[Adapter / Facade]
    Registry[Step Registry]
    Strategy[Transform Strategy]
  end

  subgraph data [Behavior in Database]
    Template[Route Template]
    Profile[Integration Profile]
    Rules[Routing Rules]
  end

  subgraph runtime [Camel Runtime]
    EIP[Enterprise Integration Patterns]
    Pipeline[Step Pipeline]
  end

  data --> Pipeline
  code --> Pipeline
  Pipeline --> EIP
```

## 2. Pattern Catalog Summary

| #  | Pattern                     | Category         | Primary Module(s)                                       |
| -- | --------------------------- | ---------------- | ------------------------------------------------------- |
| 1  | Layered Architecture        | Architectural    | All                                                     |
| 2  | Control Plane / Data Plane  | Architectural    | `h2h-admin-api`, `h2h-runtime`                          |
| 3  | Composable Library Platform | Architectural    | `h2h-runtime`, all capability JARs                      |
| 4  | Thin Runtime Shell          | Architectural    | `h2h-runtime`                                           |
| 5  | Event-Driven Architecture   | Architectural    | `h2h-mq-adapter`, `h2h-config-runtime`                  |
| 6  | Gateway / Perimeter         | Architectural    | Gateway (infra), `h2h-file-adapter`                     |
| 7  | Adapter                     | Structural       | `h2h-file-adapter`, `h2h-mq-adapter`, `h2h-transform-*` |
| 8  | Facade                      | Structural       | `h2h-finacle-wrapper`                                   |
| 9  | Bridge                      | Structural       | Custom Camel components in wrapper JARs                 |
| 10 | Composite                   | Structural       | `h2h-runtime`                                           |
| 11 | Plugin Module               | Structural       | All `*AutoConfiguration` classes                        |
| 12 | Strategy                    | Behavioral       | `h2h-transform-core`                                    |
| 13 | Template Method             | Behavioral       | Route templates in DB + `h2h-payments-routes`           |
| 14 | Chain of Responsibility     | Behavioral       | `StepExecutor`, `h2h-camel-core`                        |
| 15 | Registry                    | Behavioral       | `StepRegistry`                                          |
| 16 | Command                     | Behavioral       | Camel `Processor` beans per step                        |
| 17 | Observer                    | Behavioral       | `ConfigEventListener`, Kafka                            |
| 18 | State Machine               | Behavioral       | Transaction lifecycle (implicit)                        |
| 19 | Message Translator          | EIP              | `h2h-transform-core`                                    |
| 20 | Content Enricher            | EIP              | `ConfigResolverProcessor`                               |
| 21 | Message Router              | EIP              | `h2h-camel-core`, routing rules in DB                   |
| 22 | Splitter / Aggregator       | EIP              | `h2h-payments-routes`                                   |
| 23 | Idempotent Receiver         | EIP              | `IdempotencyProcessor`                                  |
| 24 | Dead Letter Channel         | EIP              | `GlobalErrorHandler` → `DLQ_MESSAGE` event              |
| 25 | Wire Tap                    | EIP              | `AuditProcessor`                                        |
| 26 | Retry / Redelivery          | EIP              | `GlobalErrorHandler`                                    |
| 27 | Circuit Breaker             | EIP / Resilience | `h2h-finacle-wrapper` internal                          |
| 28 | Correlation Identifier      | EIP              | `CorrelationIdProcessor`                                |
| 29 | Polling Consumer            | EIP              | `h2h-file-adapter` (SFTP poll)                          |
| 30 | Externalized Configuration  | Configuration    | `h2h-config-store`, `h2h-config-runtime`                |
| 31 | Configuration as Data       | Configuration    | PostgreSQL config tables                                |
| 32 | Cache-Aside                 | Configuration    | `ConfigCache`, `ConfigResolver`                         |
| 33 | Publish–Subscribe           | Configuration    | `CONFIG_PUBLISHED` event (`event_channel_def`)          |
| 34 | Feature Toggle              | Configuration    | `h2h.modules.*.enabled`                                 |
| 35 | Bill of Materials (BOM)     | Build            | `h2h-bom`                                               |
| 36 | Saga (optional)             | Resilience       | Camunda workflows                                       |
| 37 | Outbox (audit stream)       | Resilience       | `AuditProcessor` → Kafka                                |
| 38 | Secrets Externalization     | Security         | `h2h-security`, Vault                                   |
| 39 | Least Privilege / RBAC      | Security         | Keycloak, `h2h-admin-api`                               |
| 40 | Segregation of Duties       | Security         | Draft → approve → publish workflow                      |

***

## 3. Architectural Patterns

### 3.1 Layered Architecture

**Intent:** Separate concerns into distinct layers with defined dependencies flowing downward.

**Layers:**

| Layer                | Responsibility                           | Modules / Components                             |
| -------------------- | ---------------------------------------- | ------------------------------------------------ |
| Client               | ERP, fintech, corporate systems          | External                                         |
| Gateway              | Protocol termination, perimeter security | Kong/Apigee, SFTP gateway                        |
| Integration          | Orchestration, transformation            | `h2h-*-routes`, `h2h-camel-core`                 |
| Processing           | Validation, idempotency, enrichment      | `h2h-camel-core`                                 |
| Core Banking         | System of record                         | `CoreBankingIntegration` ← `h2h-finacle-wrapper` |
| Control & Monitoring | Admin, audit, recon                      | `h2h-admin-api`, admin UI                        |

**Rules:**

* Upper layers depend on lower layers, never the reverse
* Control layer configures integration layer but is not in the transaction hot path

**See:** [Architecture Overview](/docs/01-architecture-overview.md)

***

### 3.2 Control Plane / Data Plane Separation

**Intent:** Separate governance and configuration (control plane) from transaction processing (data plane).

| Plane             | Components                                        | Characteristics                |
| ----------------- | ------------------------------------------------- | ------------------------------ |
| **Control plane** | Admin portal, `h2h-admin-api`, config DB, Camunda | Human workflows, CRUD, publish |
| **Data plane**    | `h2h-runtime`, Camel routes, Finacle calls        | High throughput, low latency   |

**Interaction:** Control plane writes to PostgreSQL → publish event → data plane reloads cache. No synchronous admin API calls during payment processing.

**See:** [Low-Code Admin Platform](/docs/05-low-code-admin-platform.md), [Database-Driven Configuration](/docs/04-database-driven-configuration.md)

***

### 3.3 Composable Library Platform (Modular Monolith)

**Intent:** Ship capabilities as versioned JAR libraries composed into one deployable, rather than a single monolithic codebase or many microservices.

**Structure:**

```
h2h-runtime (deployable)
    ├── h2h-payments-routes
    ├── h2h-finacle-wrapper
    ├── h2h-file-adapter
    ├── h2h-camel-core
    └── h2h-config-runtime
```

**Benefits:**

* Update `h2h-finacle-wrapper` without touching payment routes
* Shared adapters across 20+ countries
* Single Camel context — no distributed transaction complexity for STP

**See:** [Modular JAR Architecture](/docs/03-modular-jar-architecture.md)

***

### 3.4 Thin Runtime Shell

**Intent:** The deployable application contains only bootstrapping; all behavior lives in library JARs.

**Module:** `h2h-runtime`

**Contains only:**

* `H2hRuntimeApplication` main class
* Infrastructure `application.yml` (DB URL, Kafka brokers — not partner config)
* Module enablement flags
* Actuator health endpoints

**Does not contain:** Business routes, Finacle logic, transforms, or partner-specific code.

***

### 3.5 Event-Driven Architecture

**Intent:** Decouple components via asynchronous events for audit, config propagation, and failure handling.

**Event codes** (physical destinations from `event_channel_def` — see [46](/docs/46-database-driven-events.md)):

| Event code         | Publisher              | Consumer               | Purpose                |
| ------------------ | ---------------------- | ---------------------- | ---------------------- |
| `AUDIT_EVENT`      | `AuditProcessor`       | OpenSearch, compliance | Immutable audit trail  |
| `CONFIG_PUBLISHED` | `ConfigVersionService` | `ConfigEventListener`  | Cache invalidation     |
| `DLQ_MESSAGE`      | `GlobalErrorHandler`   | Ops dashboard          | Dead letter processing |
| `PAYMENT_POSTED`   | Payment routes         | Reconciliation         | Downstream processing  |

**Module:** `h2h-mq-adapter`

**See:** [Technology Stack](/docs/02-technology-stack.md)

***

### 3.6 Gateway / Perimeter Pattern

**Intent:** Terminate client protocols at the edge; integration layer sees normalized messages.

| Gateway            | Terminates                 | Forwards to             |
| ------------------ | -------------------------- | ----------------------- |
| SFTP gateway       | SSH, file pickup           | Camel file ingest route |
| API gateway (Kong) | TLS, API keys, rate limits | Camel HTTP route        |
| MQ ingress         | Kafka/JMS protocol         | Camel Kafka consumer    |

**Module:** `h2h-file-adapter` (SFTP side); API gateway is infrastructure.

***

## 4. Structural Patterns

### 4.1 Adapter

**Intent:** Convert the interface of an external system into an interface the platform expects.

| Adapter Module           | Adapts              | Internal Interface                                |
| ------------------------ | ------------------- | ------------------------------------------------- |
| `h2h-file-adapter`       | SFTP, file system   | `DynamicSftpEndpoint`, file staging API           |
| `h2h-mq-adapter`         | Kafka, JMS          | Standard Kafka producer/consumer with H2H headers |
| `h2h-transform-iso20022` | ISO 20022 XML       | Canonical payment model                           |
| `h2h-transform-mt940`    | SWIFT MT940         | Canonical statement model                         |
| `h2h-ack-nack`           | Partner ACK formats | Internal ACK generation API                       |

**Example:** `DynamicSftpEndpoint` reads SFTP host, paths, and credentials from `IntegrationProfile` (DB + Vault) and builds a standard Camel SFTP URI internally.

***

### 4.2 Facade + Strategy (Core Banking)

**Intent:** Provide a simplified unified interface over a complex subsystem; allow CBS implementations to vary.

| Layer           | Module                 | Pattern                                                      |
| --------------- | ---------------------- | ------------------------------------------------------------ |
| Contract        | `h2h-core-banking-api` | **Strategy** — `CoreBankingIntegration` interface            |
| Finacle adapter | `h2h-finacle-wrapper`  | **Facade** — `FinacleCoreBankingIntegration` hides FCJ/FCUBS |
| Routes          | `h2h-*-routes`         | Depend on interface only (**Dependency Inversion**)          |

**Interface:** `CoreBankingIntegration` (in `h2h-core-banking-api`)

**Finacle implementation hides:**

* FCJ API client (`FcjClient` in `internal/`)
* FCUBS Web Services client (`FcubsClient` in `internal/`)
* Connection pooling (`FinacleConnectionPool`)
* Circuit breaker and timeout logic

**Consumers:** `h2h-payments-routes`, `h2h-collections-routes` — inject `CoreBankingIntegration`, never FCJ/FCUBS SDK types.

```java
// Stable CBS contract — h2h-core-banking-api
public interface CoreBankingIntegration {
    PaymentResult postPayment(PaymentRequest request, CoreBankingContext ctx);
    AccountInfo inquireAccount(AccountInquiry inquiry, CoreBankingContext ctx);
}
```

**Injection:** `FinacleAutoConfiguration` registers `FinacleCoreBankingIntegration` as the `CoreBankingIntegration` bean; `finacle:` Camel component receives it via constructor injection.

**See:** [43 Core Banking Integration API](/docs/43-core-banking-integration-api.md), [Modular JAR Architecture](/docs/03-modular-jar-architecture.md) §4

***

### 4.3 Bridge

**Intent:** Decouple abstraction from implementation; allow both to vary independently.

**Implementation:** Custom Camel components bridge the route DSL to wrapper JAR internals.

| URI Scheme            | Bridges to                                      |
| --------------------- | ----------------------------------------------- |
| `finacle:postPayment` | Injected `CoreBankingIntegration.postPayment()` |
| `crypto:pgpDecrypt`   | `PgpService.decrypt()` via Vault key ref        |
| `transform:apply`     | `TransformEngine` selected by DB spec           |
| `idempotent:check`    | `IdempotencyStore`                              |

**Module:** `camel/` package inside each wrapper JAR.

***

### 4.4 Composite

**Intent:** Compose objects into tree structures; treat individual and composite objects uniformly.

**Implementation:** `h2h-runtime` composes all enabled JAR modules into one running application. Each JAR contributes routes, components, and auto-configuration. The runtime treats the whole as a single deployable unit.

**Composition mechanism:** Maven dependencies + Spring Boot auto-configuration imports.

***

### 4.5 Plugin Module (Spring Auto-Configuration)

**Intent:** Enable optional capabilities at deploy time without modifying the runtime codebase.

**Implementation:**

```java
@AutoConfiguration
@ConditionalOnProperty(name = "h2h.modules.payments.enabled", havingValue = "true")
public class PaymentsRoutesAutoConfiguration {
    @Bean
    RouteBuilder bulkPaymentRouteBuilder(...) { ... }
}
```

**Registration:** `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`

**Modules using this pattern:** Every `h2h-*-routes`, `h2h-finacle-wrapper`, `h2h-file-adapter`, etc.

***

## 5. Behavioral Patterns

### 5.1 Strategy

**Intent:** Define a family of algorithms (transform engines), encapsulate each, and make them interchangeable at runtime.

**Module:** `h2h-transform-core`

**Context:** `TransformProducer` reads `TransformSpec.engine` from database.

**Strategies:**

| Engine    | Implementation       |
| --------- | -------------------- |
| `JOLT`    | `JoltTransformer`    |
| `JSONATA` | `JsonataTransformer` |
| `XSLT`    | `XsltTransformer`    |

**Selection:** Database-driven — admins choose engine per transform spec in the mapping editor. No code change to switch engines.

```java
Object result = switch (spec.getEngine()) {
    case "JOLT"    -> joltTransformer.transform(body, spec.getSpecBody());
    case "JSONATA" -> jsonataTransformer.transform(body, spec.getSpecBody());
    case "XSLT"    -> xsltTransformer.transform(body, spec.getSpecBody());
    default -> throw new UnsupportedTransformEngineException(spec.getEngine());
};
```

***

### 5.2 Template Method

**Intent:** Define the skeleton of an algorithm in a base structure; subclasses (or configuration) override specific steps.

**Implementation:** Two-level template:

| Level                    | What is fixed                                            | What varies                             |
| ------------------------ | -------------------------------------------------------- | --------------------------------------- |
| **Route template** (DB)  | Step types available (PGP\_DECRYPT, FINACLE\_POST, etc.) | Which steps run, order, per-step config |
| **Route skeleton** (JAR) | Overall flow: ingest → resolve → execute → finalize      | Nothing — routes are generic            |

**Example template:** `BULK_PAYMENT_STP_V1` in `route_template` table defines step sequence. Partner A and Partner B use the same template with different transform specs.

**Modules:** `h2h-payments-routes` (skeleton), `h2h-config-store` (template data)

***

### 5.3 Chain of Responsibility

**Intent:** Pass a request along a chain of handlers; each handler decides whether to process or pass on.

**Implementation:** `StepExecutor` iterates `List<RouteStep>` from the database, invoking the matching `Processor` for each `step_code`.

**Module:** `h2h-camel-core`

```java
// Each step is a handler in the chain
for (RouteStep step : steps) {
    Processor processor = stepRegistry.get(step.getStepCode());
    processor.process(exchange);
}
```

**Error handling per step:** `route_step.on_error` column defines RETRY, DLQ, or MANUAL behavior.

***

### 5.4 Registry

**Intent:** Provide a global access point for locating named services (step implementations).

**Module:** `h2h-camel-core`

**Class:** `StepRegistry`

**Maps:**

```
PGP_DECRYPT       → pgpDecryptProcessor
FILE_VALIDATE     → fileValidateProcessor
TRANSFORM_INBOUND → transformProcessor
FINACLE_POST      → finaclePostProcessor
TRANSFORM_ACK     → ackGenerateProcessor
...
```

**Validation on publish:** Admin API verifies all `step_code` values in a route template exist in `StepRegistry.registeredStepCodes()`.

***

### 5.5 Command

**Intent:** Encapsulate a request as an object, allowing parameterization and queuing of operations.

**Implementation:** Each Camel `Processor` bean is a command — a discrete, named, testable unit of work invoked by the step executor.

| Command (Processor)    | Action               |
| ---------------------- | -------------------- |
| `pgpDecryptProcessor`  | Decrypt file         |
| `finaclePostProcessor` | Post to core banking |
| `ackGenerateProcessor` | Generate ACK file    |

**Benefits:** Unit test each command in isolation; compose commands via DB template.

***

### 5.6 Observer

**Intent:** Define a one-to-many dependency so when one object changes state, all dependents are notified.

**Implementation:**

| Subject                          | Observers                                 | Event                                   |
| -------------------------------- | ----------------------------------------- | --------------------------------------- |
| `ConfigVersionService` (publish) | `ConfigEventListener` on all runtime pods | `CONFIG_PUBLISHED` via `EventPublisher` |
| Payment route (success/failure)  | `AuditProcessor`, recon consumers         | `AUDIT_EVENT`, `PAYMENT_POSTED`         |

**Module:** `h2h-config-runtime` (`ConfigEventListener`), `h2h-mq-adapter`

***

### 5.7 State Machine (Implicit)

**Intent:** Model transaction lifecycle as discrete states with defined transitions.

**States:**

```
INGESTED → VALIDATED → TRANSFORMED → IDEMPOTENCY_CHECK
    → PROCESSING → POSTED → ACKNOWLEDGED
    → FAILED → RETRY | EXCEPTION | DLQ
    → DUPLICATE (terminal)
```

**Implementation:** `exchange.setProperty("h2h.status", ...)` updated by processors. Operations dashboard reads status from transaction metadata store.

**See:** [Architecture Overview](/docs/01-architecture-overview.md) §10

***

## 6. Enterprise Integration Patterns (EIP)

Apache Camel implements these patterns. Below is how each maps to platform components.

### 6.1 Message Translator

**Intent:** Convert message format A to format B.

| Translation                 | Module                   |
| --------------------------- | ------------------------ |
| CSV → canonical             | `h2h-transform-core`     |
| ISO 20022 → canonical       | `h2h-transform-iso20022` |
| Canonical → Finacle request | `h2h-finacle-wrapper`    |
| Canonical → ACK CSV         | `h2h-ack-nack`           |

**Spec source:** `transform_spec` table (engine + spec\_body).

***

### 6.2 Content Enricher

**Intent:** Add data to a message from an external source.

**Implementation:** `ConfigResolverProcessor` enriches the exchange with the full `IntegrationProfile` (channel config, transforms, rules, ACK template) loaded from database.

**Module:** `h2h-camel-core`

***

### 6.3 Message Router

**Intent:** Route messages to different destinations based on conditions.

**Implementation:**

* **Code:** Camel `choice()` EIP in route skeletons
* **Config:** `routing_rule` table — conditions evaluated at runtime (amount thresholds, country, product)

**Example rule:** IF `amount > 50000000` THEN `action = MANUAL_REVIEW`

***

### 6.4 Splitter / Aggregator

**Intent:** Split a batch message into individual items; optionally aggregate results.

**Implementation:** Bulk payment route uses Camel `split()` with streaming:

```java
.split(body(), aggregationStrategy)
    .streaming()
    .parallelProcessing()
    .to("direct:process-single-payment")
.end()
```

**Module:** `h2h-payments-routes`

**Config:** `profile.processingConfig.threadPoolSize`, `batchSize` from database.

***

### 6.5 Idempotent Receiver

**Intent:** Ensure duplicate messages are detected and handled without side effects.

**Implementation:** `IdempotencyProcessor` checks `IdempotencyStore` before Finacle post.

**Key construction:** Hash of partner ID + file hash + line reference (configurable per profile).

**Module:** `h2h-camel-core`

**Store:** Redis or PostgreSQL (configurable).

***

### 6.6 Dead Letter Channel

**Intent:** Route failed messages to a dedicated channel for inspection and reprocessing.

**Implementation:** `GlobalErrorHandler` publishes `DLQ_MESSAGE` via `EventPublisher` after retries exhausted.

**Module:** `h2h-camel-core`

**Consumer:** Operations dashboard DLQ browser.

***

### 6.7 Wire Tap

**Intent:** Send a copy of the message to a separate channel without affecting the main flow.

**Implementation:** `AuditProcessor` publishes `AUDIT_EVENT` at each step — a tap on the main pipeline.

**Module:** `h2h-camel-core`

***

### 6.8 Retry / Redelivery

**Intent:** Automatically retry failed operations with configurable delay.

**Implementation:** Global Camel `onException` with `maximumRedeliveries`, `redeliveryDelay`, `useExponentialBackOff()`.

**Config:** `h2h.maxRetries` from integration profile.

**Module:** `h2h-camel-core` (`GlobalErrorHandler`)

***

### 6.9 Circuit Breaker

**Intent:** Stop calling a failing external service to allow recovery.

**Implementation:** Inside `h2h-finacle-wrapper` — if Finacle error rate exceeds threshold, circuit opens and payments queue for retry instead of hammering core banking.

**Module:** `h2h-finacle-wrapper` (`internal/` package)

***

### 6.10 Correlation Identifier

**Intent:** Bind related messages with a unique ID propagated across all components.

**Implementation:** `CorrelationIdProcessor` sets `h2h.correlationId` on exchange; propagated via Camel headers, Kafka message headers, MDC logging, and Finacle request metadata.

**Module:** `h2h-camel-core`

**Header:** `X-Correlation-Id`

***

### 6.11 Polling Consumer

**Intent:** Periodically poll an external source for new messages.

**Implementation:** `DynamicSftpEndpoint` (scheduled poll) reads cron from `channel_config.poll_cron` in database.

**Module:** `h2h-file-adapter`

***

## 7. Configuration Patterns

### 7.1 Externalized Configuration

**Intent:** Store all environment-specific and partner-specific settings outside application code.

| Config type                       | Storage                  | NOT stored in         |
| --------------------------------- | ------------------------ | --------------------- |
| Partner profiles, mappings, rules | PostgreSQL               | Java code, YAML       |
| Infrastructure (DB URL, Kafka)    | K8s ConfigMap / env vars | Partner config tables |
| Secrets                           | Vault                    | Database, code, YAML  |

**Modules:** `h2h-config-store`, `h2h-config-runtime`

***

### 7.2 Configuration as Data

**Intent:** Treat integration behavior as data records that admins manage through a UI — the low-code foundation.

**Examples:** `integration_profile`, `route_template`, `transform_spec`, `routing_rule` — all database tables editable via admin portal.

**See:** [Database-Driven Configuration](/docs/04-database-driven-configuration.md)

***

### 7.3 Cache-Aside

**Intent:** Application manages cache explicitly — read from cache first, load from DB on miss, invalidate on change.

**Implementation:**

```
ConfigResolver.resolve(key)
    → ConfigCache.get(key)
        → hit: return profile
        → miss: load from PostgreSQL → put in cache → return
```

**Invalidation:** `CONFIG_PUBLISHED` event → `ConfigEventListener` evicts affected keys.

**Module:** `h2h-config-runtime` (`ConfigCache`, `ConfigResolver`)

**Hot path target:** One DB read per batch at profile resolution; zero per payment line.

***

### 7.4 Publish–Subscribe (Config Propagation)

**Intent:** When configuration is published, all runtime instances are notified to refresh.

**Flow:**

1. Supervisor approves → `config_version.status = PUBLISHED`
2. `ConfigVersionService` publishes `CONFIG_PUBLISHED`
3. All pods' `ConfigEventListener` receives event
4. `ConfigCache` evicts keys for affected partner/country
5. Next transaction loads fresh config

***

### 7.5 Feature Toggle

**Intent:** Enable or disable capabilities at deploy time without code changes.

**Implementation:**

```yaml
h2h:
  modules:
    payments:
      enabled: true
    collections:
      enabled: false
    statements:
      enabled: false
```

**Mechanism:** `@ConditionalOnProperty` on each module's `AutoConfiguration`.

***

### 7.6 Bill of Materials (BOM)

**Intent:** Centralize dependency version management for a compatible set of modules.

**Module:** `h2h-bom`

**Usage:** Runtime and all JARs import `h2h-bom` for aligned versions of Camel, Spring Boot, and internal modules.

***

## 8. Resilience & Operational Patterns

### 8.1 Saga (Optional)

**Intent:** Manage long-running distributed transactions with compensating actions.

**Use cases:**

* Partner onboarding approval (Camunda)
* Manual exception review and reprocess
* Multi-step treasury flows

**Tool:** Camunda BPM (human task workflows, not payment hot path).

***

### 8.2 Outbox (Audit Stream)

**Intent:** Reliably publish events by writing to an outbound channel as part of processing.

**Implementation:** `AuditProcessor` publishes to Kafka within the same processing thread. For guaranteed audit delivery, audit events can be written to a local outbox table and published by a separate poller (enhancement if required).

**Current:** Direct Kafka publish with at-least-once semantics.

***

### 8.3 Country Pack

**Intent:** Deploy localized behavior as a configuration bundle, not a code fork.

**Implementation:** Import JSON/YAML bundle into config DB — transforms, rules, calendars, schedules for a country.

**Module:** `h2h-config-store` (import API)

**See:** [Multi-Country Deployment](/docs/07-multi-country-deployment.md)

***

## 9. Security Patterns

### 9.1 Secrets Externalization

**Intent:** Keep all credentials and keys out of code and database.

**Implementation:** `VaultCredentialResolver` in `h2h-security`; database stores `credential_ref` (Vault path only).

***

### 9.2 Defense in Depth

**Layers:** Gateway TLS → service mesh mTLS → Vault → PGP file encryption → RBAC on admin.

***

### 9.3 Least Privilege (RBAC)

**Implementation:** Keycloak roles scoped by `organization → country → partner → product → environment`.

**See:** [Personas and RBAC](/docs/06-personas-and-rbac.md)

***

### 9.4 Segregation of Duties

**Implementation:** Draft → `PENDING_APPROVAL` → `PUBLISHED` workflow. Onboarding officer cannot publish; supervisor cannot edit Vault secrets.

***

## 10. Anti-Patterns (Explicitly Avoided)

| Anti-Pattern                  | Why Avoided                          | Enforced By                          |
| ----------------------------- | ------------------------------------ | ------------------------------------ |
| **Hardcoded partner logic**   | Breaks low-code and multi-country    | ArchUnit, code review                |
| **God object / monolith**     | Prevents independent JAR updates     | Module boundaries, dependency rules  |
| **Config in code/resources**  | Requires redeploy per partner change | CI grep, ArchUnit                    |
| **Secrets in database**       | Security/compliance violation        | Schema validation, security review   |
| **Microservices per partner** | Unnecessary ops complexity for STP   | Architecture decision                |
| **Low-code on hot path**      | Performance and audit risk           | JARs provide steps; DB selects steps |

***

## 11. Pattern Interaction — End-to-End Example

**Scenario:** ACME Corp uploads an encrypted bulk payment CSV via SFTP.

```mermaid
sequenceDiagram
  participant SFTP as SFTP Gateway
  participant Ingest as File Ingest Route
  participant Resolver as ConfigResolver
  participant Pipeline as StepExecutor
  participant Registry as StepRegistry
  participant CBS as CoreBankingIntegration
  participant Audit as AuditProcessor
  participant Kafka

  SFTP->>Ingest: New file (Polling Consumer)
  Ingest->>Ingest: CorrelationIdProcessor
  Ingest->>Resolver: resolve(ACME, BULK_PAYMENT)
  Note over Resolver: Cache-Aside pattern
  Resolver-->>Ingest: IntegrationProfile
  Ingest->>Pipeline: Execute template steps
  loop Each step (Chain of Responsibility)
    Pipeline->>Registry: get(stepCode)
    Registry-->>Pipeline: Processor (Command)
    Pipeline->>Pipeline: PGP Decrypt (Adapter)
    Pipeline->>Pipeline: Transform (Strategy/JOLT)
    Pipeline->>Pipeline: Idempotency Check (Idempotent Receiver)
    Pipeline->>Finacle: postPayment (Facade)
    Pipeline->>Audit: Wire Tap
    Audit->>EventBus: AUDIT_EVENT
  end
  Pipeline->>Pipeline: Generate ACK (Message Translator)
```

| Step                | Pattern(s) Applied                                 |
| ------------------- | -------------------------------------------------- |
| SFTP pickup         | Polling Consumer, Adapter, Gateway                 |
| Correlation ID      | Correlation Identifier                             |
| Load partner config | Cache-Aside, Content Enricher, Externalized Config |
| PGP decrypt         | Adapter, Secrets Externalization                   |
| CSV transform       | Strategy (JOLT), Message Translator                |
| Duplicate check     | Idempotent Receiver                                |
| Finacle post        | Facade, Circuit Breaker                            |
| Audit emit          | Wire Tap, Observer, Outbox                         |
| ACK delivery        | Message Translator, Adapter                        |
| On failure          | Retry, Dead Letter Channel                         |

***

## 12. Module-to-Pattern Quick Reference

| Module                | Patterns                                                                                                      |
| --------------------- | ------------------------------------------------------------------------------------------------------------- |
| `h2h-runtime`         | Thin Runtime Shell, Composite, Plugin Module                                                                  |
| `h2h-bom`             | Bill of Materials                                                                                             |
| `h2h-common`          | Shared value objects (no pattern — domain models)                                                             |
| `h2h-config-api`      | Facade (interface boundary)                                                                                   |
| `h2h-config-store`    | Externalized Configuration, Configuration as Data                                                             |
| `h2h-config-runtime`  | Cache-Aside, Observer, Registry (config)                                                                      |
| `h2h-camel-core`      | Chain of Responsibility, Registry, Command, Idempotent Receiver, Wire Tap, Retry, DLQ, Correlation Identifier |
| `h2h-security`        | Adapter, Secrets Externalization                                                                              |
| `h2h-finacle-wrapper` | Facade, Adapter, Bridge, Circuit Breaker                                                                      |
| `h2h-file-adapter`    | Adapter, Bridge, Polling Consumer                                                                             |
| `h2h-mq-adapter`      | Adapter, Event-Driven, Observer                                                                               |
| `h2h-transform-core`  | Strategy, Message Translator                                                                                  |
| `h2h-payments-routes` | Template Method, Splitter, Message Router                                                                     |
| `h2h-ack-nack`        | Message Translator, Adapter                                                                                   |
| `h2h-admin-api`       | Control Plane, Segregation of Duties                                                                          |
| `h2h-reconciliation`  | Content Enricher, Message Router                                                                              |

***

## 13. Related Documents

* [Architecture Overview](/docs/01-architecture-overview.md)
* [Modular JAR Architecture](/docs/03-modular-jar-architecture.md)
* [Database-Driven Configuration](/docs/04-database-driven-configuration.md)
* [Camel Integration Patterns](/docs/08-camel-integration-patterns.md)
* [Security and Compliance](/docs/09-security-and-compliance.md)
* [Glossary](/docs/12-glossary.md)
* [Extensibility Framework](/docs/14-extensibility-framework.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://host2host.onibonje.com/docs/13-design-patterns.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
