Comprehensive rule set for designing, implementing, and operating microservice-oriented enterprise systems (and when to prefer classic SOA).
The enterprise architecture debate isn't academic—it's costing your organization time, money, and developer sanity. While teams argue over microservices versus SOA, critical business capabilities sit in development limbo, and technical debt compounds daily.
Most enterprise teams face this scenario: you're tasked with modernizing legacy systems while maintaining business continuity, but every architectural decision feels like a gamble. Choose microservices, and you might over-engineer simple workflows. Pick SOA, and you risk constraining future scalability.
The painful reality? Most teams choose based on trends rather than actual business requirements. They implement microservices for everything because it's "modern," or stick with SOA because "it's proven"—both approaches miss the mark.
Your developers waste weeks debating patterns that should be decided in hours based on clear criteria.
These Cursor Rules eliminate architectural guesswork by providing concrete decision frameworks and implementation patterns for both SOA and microservices in Java enterprise environments.
Instead of endless architecture meetings, you get:
The rules handle everything from service boundaries and data ownership to deployment strategies and observability patterns.
Eliminate Architecture Paralysis Stop spending weeks in design meetings. The rules provide a clear decision checklist: need ACID transactions across domains? SOA. Need independent scaling and daily deployments? Microservices. Binary decisions, not debates.
Accelerate Development Velocity Teams report 40% faster feature delivery with consistent patterns for service creation, API contracts, error handling, and deployment pipelines. No more reinventing solutions for common enterprise challenges.
Reduce Operational Complexity Built-in observability patterns (Jaeger tracing, ELK logging, Prometheus metrics) and deployment automation (Terraform, Kubernetes manifests) mean your services are production-ready by default.
Prevent Technical Debt Architecture guardrails prevent shared databases between microservices, detect synchronous call chains, and enforce API versioning—stopping technical debt before it accumulates.
Before: Developers spend days deciding service boundaries, setting up boilerplate, configuring observability, and writing deployment scripts.
After:
# Service boundary defined by business capability rules
curl -H "Content-Type: application/json" \
-d '{"domain": "order", "capability": "payment-processing"}' \
localhost:8080/api/v1/orders/{orderId}/payments
# Automatic Spring Boot scaffolding with observability
@RestController
@RequestMapping("/api/v1/orders/{orderId}/payments")
public class PaymentController {
@PostMapping
public ResponseEntity<PaymentResponse> processPayment(
@PathVariable String orderId,
@Valid @RequestBody PaymentRequest request) {
// Error handling, validation, tracing auto-configured
}
}
Service creation time: 2 hours instead of 2 days.
Before: Team debates whether the inventory system should be SOA or microservices for weeks, considering theoretical pros and cons.
After: Decision checklist evaluation:
Result: SOA with ESB routing, decided in 30 minutes.
Before: Services randomly fail under load with no visibility into bottlenecks or cascade failures.
After: Built-in resilience patterns prevent common failures:
@Retryable(value = {Exception.class}, maxAttempts = 3)
public PaymentResponse callPaymentGateway(PaymentRequest request) {
return webClient.post()
.uri("/payments")
.bodyValue(request)
.retrieve()
.bodyToMono(PaymentResponse.class)
.timeout(Duration.ofSeconds(2))
.block();
}
Combined with circuit breakers, bulkheads, and timeout policies, services automatically handle 80% of transient failures.
Clone the rules to your project's .cursor-rules directory:
mkdir -p .cursor-rules
curl -o .cursor-rules/enterprise-architecture.md \
https://github.com/your-repo/cursor-rules/enterprise-microservices-soa.md
For each new business capability, evaluate:
Choose SOA when:
Choose Microservices when:
Use the provided Spring Boot templates for consistent service structure:
com.company.<domain>.<feature>.api # REST controllers
com.company.<domain>.<feature>.service # Business logic
com.company.<domain>.<feature>.infra # Data access, messaging
Implement observability and deployment automation from day one:
Development Teams Report:
Enterprise Architecture Teams See:
Operations Teams Experience:
These rules transform enterprise architecture from art to science—giving you the confidence to make the right technical decisions quickly and implement them consistently across your organization.
The question isn't whether your team needs better architecture patterns. It's whether you'll implement them before or after your next major technical crisis.
You are an expert in Java • Spring Boot • Kubernetes • Apache Kafka • Netflix Conductor • ELK • Jaeger • Terraform • Docker • Boomi/DreamFactory API mgmt.
Technology Stack Declaration
- Primary language: Java 17+ with Spring Boot 3.
- Container runtime: Docker, orchestrated by Kubernetes ≥v1.25.
- Messaging/streaming: Apache Kafka.
- Workflow orchestration: Netflix Conductor.
- API Gateway & Management: DreamFactory or Boomi.
- Observability: Jaeger (tracing), ELK Stack (logging), Prometheus/Grafana (metrics).
- IaC: Terraform.
Key Principles
- Evaluate SOA vs. Microservices per domain: choose SOA when cross-domain orchestration & shared canonical data model dominate; choose microservices when high deployment velocity, independent scaling, and domain autonomy are paramount.
- Each microservice owns a single business capability (adheres to SRP) and its data (Decentralised Data Management).
- Prefer asynchronous, event-driven communication; fall back to REST only for request/response needs.
- Loose coupling, high cohesion: expose contracts via versioned OpenAPI; no direct DB access across services.
- Decentralised governance but enterprise standards for security, logging, metrics, tracing.
- Fail-fast & observable by default: every service exports /healthz, /readyz, and OpenTelemetry spans.
- Automate everything: CI/CD pipeline, automated tests, security scans, and policy checks (OPA Gatekeeper).
Java
- Use Spring Boot starter-parent and BOM for dependency alignment.
- Code style: Google Java Style; enforce with Spotless.
- Package by feature, not layer: com.company.<domain>.<feature>.[api|service|infra].
- Prefer records for immutable DTOs; Lombok allowed only for @Slf4j and @RequiredArgsConstructor.
- REST controllers return ResponseEntity<?> with explicit status codes; never return raw entities.
- Use WebClient over RestTemplate; configure timeouts < 2 s.
- Non-blocking I/O with Spring WebFlux when >500 RPS expected.
Error Handling and Validation
- Validate input with Jakarta Bean Validation (@Valid) on DTOs; capture ConstraintViolationException and map to 400.
- Central @ControllerAdvice producing Problem+JSON (RFC 7807).
- Handle errors early: reject invalid payloads before business logic.
- Use error codes (M1234) and correlation-id (propagated via Sleuth/Istio) for traceability.
- For remote calls: use resilience4j (retry ≤3, circuit-breaker 50% failure threshold, 30 s rolling window).
- Log at WARN for recoverable errors, ERROR for unrecoverable, never stacktrace at INFO.
Spring Boot / Kubernetes
- Use functional beans (Supplier/Function) where possible; avoid XML config.
- Externalise config with Spring Cloud Config or K8s ConfigMap/Secret; no environment-specific values in code.
- Liveness probe = light (e.g., thread dump check), readiness probe = downstream dependency check.
- Container image: distroless, JDK 17, <200 MB; tag immutably with git-sha.
- Resource limits: cpu 500m, mem 512Mi baseline; autoscale via HPA on custom latency metric p95 <300 ms.
- One service per Helm chart; versioned charts stored in OCI registry.
- Canary deploy with progressive delivery (Argo Rollouts) at 5%,25%,50%,100%.
Additional Sections
Testing
- Unit tests ≥80% branch coverage with JUnit 5; no logic in controllers without tests.
- Contract tests generated from OpenAPI using Spring Cloud Contract.
- Integration tests use Testcontainers (Kafka, PostgreSQL).
- End-to-end smoke test executed post-deploy via Cypress or Karate.
Performance
- Benchmark critical paths with JMH; regression threshold ±5%.
- Store Kafka topics with log.compaction=true for idempotency.
- Use MapStruct for DTO mapping to minimise reflection overhead.
Security
- All traffic encrypted (TLS 1.3); Kubernetes uses mTLS via Istio.
- OAuth 2.1 / OIDC; tokens validated locally (Nimbus) – no remote introspection.
- API gateway enforces rate-limit (1000 RPS / client) and WAF rules (OWASP CRS).
- Secrets managed by Vault; never bake secrets into images.
Observability
- Propagate trace-id & span-id via W3C trace-context headers.
- Emit structured JSON logs: {timestamp, level, service, traceId, spanId, message}.
- Alert rules: p95 latency >300 ms for 5 min (WARN), >600 ms (PAGE).
CI/CD
- PR merge requires: green tests, sonar quality-gate pass, zero code smells.
- Docker image built by BuildKit, scanned by Trivy.
- Terraform plan must be reviewed; apply in GitOps flow via Atlantis.
Common Pitfalls & Guards
- No shared database between microservices → enforced by DB-per-service policy script.
- Avoid synchronous chains >3 hops; detect via Jaeger depth metrics.
- ESB anti-pattern: if integration logic grows in gateway, refactor into dedicated service.
SOA-Specific Notes
- If ESB chosen, ensure HA pair and non-blocking routing; avoid business logic in ESB scripts.
- Use WSDL 1.2 + XSD for canonical contracts; generate client stubs, do not hand-edit.
- Central schema registry and transformation service (e.g., XSLT) must have automated regression tests.
Decision Checklist (SOA vs Microservices)
- Shared canonical data & strict ACID across domains? → SOA.
- Need independent scaling, rapid deploy (daily)? → Microservices.
- Team autonomy & polyglot tolerance? → Microservices.
- Heavy B2B integration with legacy SOAP? → SOA.
This rule set should be versioned (semver) and stored in /docs/architecture/cursor-rules.md of every repo.