Transactional Architecture Builder
A comprehensive architecture generator that creates complete transactional systems with microservices, domain gateways, federated GraphQL APIs, and supporting infrastructure for enterprise-scale applications.
Overview
This archetype orchestrates multiple component archetypes to build a full transactional architecture following Domain-Driven Design (DDD) principles. It generates a polyglot microservices ecosystem with Java services, Rust-based federation gateway, and comprehensive documentation.
Technology Stack
Core Technologies
- Java Spring Boot: Microservices and domain services
- Rust: High-performance GraphQL federation gateway
- GraphQL: API federation and domain gateways
- gRPC: Inter-service communication
- PostgreSQL: Transactional data storage
- Redis: Caching and session management
Supporting Infrastructure
- Docker: Containerization
- Kubernetes: Orchestration
- Prometheus: Monitoring
- mdBook: Architecture documentation
- GitHub Actions: CI/CD pipelines
Architecture Components
The builder generates a complete ecosystem with the following components:
1. Federated GraphQL Gateway (Rust)
- Purpose: Single entry point for all client applications
- Technology: Rust with Apollo Router
- Features: Schema federation, query planning, authentication
- Performance: High-throughput, low-latency gateway
2. Domain Gateway (Java)
- Purpose: Domain-specific GraphQL APIs
- Technology: Java Spring Boot with GraphQL
- Features: Domain modeling, data fetching, business logic
- Integration: Connects to multiple microservices
3. Core Services (Java)
- Service Types: Business logic services
- Orchestrators: Workflow coordination services
- Adapters: External system integration services
- Assessors: Data validation and assessment services
4. Platform Libraries (Java)
- Shared Components: Common utilities and frameworks
- Cross-cutting Concerns: Logging, monitoring, security
- Data Access: Repository patterns and data mappers
5. Documentation (mdBook)
- Architecture Documentation: System design and patterns
- API Documentation: GraphQL schema and REST endpoints
- Deployment Guides: Operations and maintenance
Generated Architecture
Key Features
Transactional Consistency
- ACID Transactions: Database transaction management
- Distributed Transactions: Cross-service consistency patterns
- Saga Pattern: Long-running transaction coordination
- Event Sourcing: Audit trail and state reconstruction
Domain-Driven Design
- Bounded Contexts: Clear service boundaries
- Aggregate Roots: Consistency boundaries
- Domain Events: Decoupled communication
- Ubiquitous Language: Consistent terminology
Performance & Scalability
- GraphQL Federation: Efficient query execution
- Caching Strategy: Multi-level caching
- Connection Pooling: Optimized database connections
- Async Processing: Non-blocking operations
Security & Compliance
- Authentication: JWT-based auth with refresh tokens
- Authorization: Role-based access control (RBAC)
- Data Protection: Encryption at rest and in transit
- Audit Logging: Complete audit trail
Project Structure
After generation, you'll have a comprehensive project structure:
transactional-architecture/
├── federation-gateway/ # Rust GraphQL Federation Gateway
│ ├── src/
│ ├── Cargo.toml
│ ├── router.yaml
│ └── Dockerfile
├── domain-gateways/
│ ├── user-domain-gateway/ # User Domain GraphQL Gateway
│ ├── order-domain-gateway/ # Order Domain GraphQL Gateway
│ └── product-domain-gateway/ # Product Domain GraphQL Gateway
├── services/
│ ├── user-service/ # User Business Logic Service
│ ├── order-service/ # Order Business Logic Service
│ ├── product-service/ # Product Business Logic Service
│ ├── order-orchestrator/ # Order Workflow Orchestrator
│ ├── payment-adapter/ # Payment System Adapter
│ └── user-assessor/ # User Validation Assessor
├── platform-libs/ # Shared Java Libraries
│ ├── common/
│ ├── data-access/
│ ├── messaging/
│ └── security/
├── infrastructure/
│ ├── docker-compose.yml # Local development setup
│ ├── kubernetes/ # K8s deployment manifests
│ ├── monitoring/ # Prometheus/Grafana configs
│ └── databases/ # Database schemas and migrations
├── documentation/ # mdBook Architecture Documentation
│ ├── src/
│ ├── book.toml
│ └── theme/
├── .github/
│ └── workflows/ # CI/CD pipelines
└── README.md
Configuration & Customization
Interactive Prompts
During generation, you'll be prompted for:
- Organization Details: Company name, domain, contact info
- Architecture Scope: Which domains and services to include
- Technology Preferences: Database choices, deployment targets
- Naming Conventions: Service names, package structures
- Feature Selection: Optional components and integrations
Generated Services
Based on your selections, the builder can generate:
- Core Services: User, Order, Product, Inventory, Payment
- Orchestrators: Complex workflow coordination
- Adapters: Integration with external systems
- Assessors: Data validation and business rule enforcement
Customization Options
- Database Selection: PostgreSQL, MySQL, CockroachDB
- Messaging: Kafka, RabbitMQ, AWS SQS
- Caching: Redis, Hazelcast, Caffeine
- Deployment: Docker Compose, Kubernetes, Cloud platforms
Development Workflow
1. Architecture Generation
# Generate the complete architecture
archetect render git@github.com:p6m-archetypes/transactional-architecture-builder.archetype.git
# Follow interactive prompts to customize
# - Organization details
# - Service selection
# - Technology choices
# - Deployment preferences
2. Local Development Setup
# Start local development environment
docker-compose up -d
# Initialize databases
./scripts/init-databases.sh
# Start services in development mode
./scripts/start-dev.sh
3. Service Development
# Navigate to a specific service
cd services/user-service
# Run tests
./gradlew test
# Start service locally
./gradlew bootRun
4. API Development
# Test GraphQL federation
curl -X POST http://localhost:4000/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ users { id name orders { id total } } }"}'
# Test individual domain gateway
curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ user(id: \"1\") { id name email } }"}'
5. Documentation
# Build architecture documentation
cd documentation
mdbook build
# Serve documentation locally
mdbook serve --open
Service Communication Patterns
GraphQL Federation
# User Domain Schema
type User @key(fields: "id") {
id: ID!
name: String!
email: String!
orders: [Order!]! @requires(fields: "id")
}
# Order Domain Schema
type Order @key(fields: "id") {
id: ID!
user: User! @provides(fields: "id")
items: [OrderItem!]!
total: Money!
status: OrderStatus!
}
# Federated Query Example
query GetUserWithOrders($userId: ID!) {
user(id: $userId) {
id
name
email
orders {
id
total
status
items {
product {
name
price
}
quantity
}
}
}
}
gRPC Service Communication
// User Service
service UserService {
rpc GetUser(GetUserRequest) returns (UserResponse);
rpc CreateUser(CreateUserRequest) returns (UserResponse);
rpc UpdateUser(UpdateUserRequest) returns (UserResponse);
rpc DeleteUser(DeleteUserRequest) returns (EmptyResponse);
}
// Order Orchestrator calling multiple services
service OrderOrchestrator {
rpc CreateOrder(CreateOrderRequest) returns (OrderResponse);
rpc ProcessPayment(ProcessPaymentRequest) returns (PaymentResponse);
rpc UpdateInventory(UpdateInventoryRequest) returns (InventoryResponse);
}
Event-Driven Communication
// Domain Event Publication
@Service
public class OrderService {
@EventListener
public void handleOrderCreated(OrderCreatedEvent event) {
// Update inventory
inventoryService.reserveItems(event.getOrderItems());
// Process payment
paymentService.processPayment(event.getPaymentInfo());
// Send notification
notificationService.sendOrderConfirmation(event.getOrder());
}
}
// Event Definition
public class OrderCreatedEvent {
private final Order order;
private final List<OrderItem> orderItems;
private final PaymentInfo paymentInfo;
// Constructor, getters, etc.
}
Deployment Options
Local Development
# docker-compose.yml
version: '3.8'
services:
federation-gateway:
build: ./federation-gateway
ports:
- "4000:4000"
environment:
- SUBGRAPH_URLS=http://user-gateway:8080/graphql,http://order-gateway:8081/graphql
user-gateway:
build: ./domain-gateways/user-domain-gateway
ports:
- "8080:8080"
environment:
- USER_SERVICE_URL=user-service:9090
user-service:
build: ./services/user-service
ports:
- "9090:9090"
environment:
- DATABASE_URL=postgresql://postgres:password@postgres:5432/userdb
postgres:
image: postgres:14
environment:
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
Kubernetes Production
# Federated gateway deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: federation-gateway
spec:
replicas: 3
selector:
matchLabels:
app: federation-gateway
template:
metadata:
labels:
app: federation-gateway
spec:
containers:
- name: gateway
image: your-registry/federation-gateway:latest
ports:
- containerPort: 4000
env:
- name: SUBGRAPH_URLS
value: "http://user-gateway:8080/graphql,http://order-gateway:8081/graphql"
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
Monitoring & Observability
Metrics Collection
// Service metrics
@RestController
public class MetricsController {
@Autowired
private MeterRegistry meterRegistry;
@GetMapping("/api/users")
public ResponseEntity<List<User>> getUsers() {
Timer.Sample sample = Timer.start(meterRegistry);
try {
List<User> users = userService.getAllUsers();
return ResponseEntity.ok(users);
} finally {
sample.stop(Timer.builder("user.service.get_users")
.description("Time taken to get all users")
.register(meterRegistry));
}
}
}
Health Checks
// Custom health indicator
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Autowired
private DataSource dataSource;
@Override
public Health health() {
try (Connection connection = dataSource.getConnection()) {
if (connection.isValid(1)) {
return Health.up()
.withDetail("database", "PostgreSQL")
.withDetail("status", "UP")
.build();
}
} catch (SQLException e) {
return Health.down()
.withDetail("database", "PostgreSQL")
.withDetail("error", e.getMessage())
.build();
}
return Health.down().build();
}
}
Testing Strategy
Unit Testing
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void shouldCreateUser() {
// Given
CreateUserRequest request = new CreateUserRequest("John", "john@example.com");
User expectedUser = new User(1L, "John", "john@example.com");
when(userRepository.save(any(User.class))).thenReturn(expectedUser);
// When
User result = userService.createUser(request);
// Then
assertThat(result.getName()).isEqualTo("John");
assertThat(result.getEmail()).isEqualTo("john@example.com");
}
}
Integration Testing
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class UserServiceIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:14")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
@Autowired
private TestRestTemplate restTemplate;
@Test
void shouldCreateAndRetrieveUser() {
// Create user
CreateUserRequest request = new CreateUserRequest("Jane", "jane@example.com");
ResponseEntity<User> createResponse = restTemplate.postForEntity("/api/users", request, User.class);
assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
// Retrieve user
Long userId = createResponse.getBody().getId();
ResponseEntity<User> getResponse = restTemplate.getForEntity("/api/users/" + userId, User.class);
assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(getResponse.getBody().getName()).isEqualTo("Jane");
}
}
Quick Start
-
Generate the architecture:
archetect render git@github.com:p6m-archetypes/transactional-architecture-builder.archetype.git -
Start local environment:
docker-compose up -d
./scripts/init-databases.sh -
Build and start services:
./scripts/build-all.sh
./scripts/start-services.sh -
Access the system:
- GraphQL Playground: http://localhost:4000
- User Domain API: http://localhost:8080/graphql
- Order Domain API: http://localhost:8081/graphql
- Documentation: http://localhost:3000
-
Run tests:
./scripts/test-all.sh
Best Practices
Architecture
- Follow Domain-Driven Design principles
- Implement proper bounded contexts
- Use event-driven architecture for loose coupling
- Design for eventual consistency
Development
- Implement comprehensive testing strategy
- Use contract testing for service boundaries
- Follow consistent coding standards
- Implement proper error handling
Operations
- Set up monitoring and alerting
- Implement distributed tracing
- Use infrastructure as code
- Plan for disaster recovery
Security
- Implement defense in depth
- Use principle of least privilege
- Regular security audits
- Keep dependencies updated