Comprehensive Rules for building enterprise-grade integrations with Apache Camel and the Enterprise Integration Patterns (EIP) ecosystem.
Enterprise integration shouldn't require months of debugging distributed transactions or hunting down why your order processing pipeline randomly fails. Yet most development teams spend 60% of their integration time troubleshooting connection failures, data transformation errors, and mysterious message routing issues instead of building business value.
You're dealing with a complex ecosystem where systems need to communicate reliably at scale:
Every enterprise faces the same integration patterns—Content-Based Routing, Message Aggregation, Dead Letter Channels, Circuit Breakers—but most teams reimplement them from scratch for each project.
These Cursor Rules transform your Apache Camel development into a systematic, pattern-driven approach that eliminates the guesswork. Instead of writing custom integration logic, you leverage battle-tested Enterprise Integration Patterns with consistent implementation standards.
What you get:
Instead of spending weeks implementing custom routing logic, you use established patterns:
// Before: Custom routing with manual error handling
public void processOrder(Order order) {
try {
if (order.getType().equals("EXPRESS")) {
expressOrderService.process(order);
} else if (order.getType().equals("STANDARD")) {
standardOrderService.process(order);
}
// ... dozens of lines of error handling, logging, retry logic
} catch (Exception e) {
// Manual DLQ implementation, logging, alerting...
}
}
// After: Pattern-driven with built-in reliability
from("kafka:orders.created?groupId=orders-sync")
.routeId("orders-sync-v1")
.validate(body().method("isValid"))
.choice()
.when(header("orderType").isEqualTo("EXPRESS"))
.to("direct:express")
.otherwise()
.to("direct:standard")
.end();
Structured error handling with automatic Dead Letter Channels and tracing means you know exactly where and why integrations fail:
.onException(Exception.class)
.handled(true)
.setHeader("fatalReason", simple("${exception.message}"))
.setHeader("fatalStack", simple("${exception.stacktrace}"))
.to("kafka:orders.dlq");
Zero-trust security becomes automatic instead of a per-integration engineering effort. Every endpoint gets OAuth2 protection without custom implementation.
Built-in patterns for exactly-once semantics, idempotent processing, and circuit breakers eliminate the common causes of integration failures.
Traditional Approach (2-3 weeks):
With These Rules (2-3 days):
from("rest:post:/customers/sync")
.routeId("customer-sync-v1")
.validate(body().method("isValid"))
.choice()
.when(header("customerType").isEqualTo("ENTERPRISE"))
.to("atlasmap:enterprise-mapping.adm")
.to("kafka:customers.enterprise")
.when(header("customerType").isEqualTo("SMB"))
.to("atlasmap:smb-mapping.adm")
.to("kafka:customers.smb")
.otherwise()
.stop()
.end();
Traditional Approach: Build custom aggregation logic with Redis, handle partial failures, implement timeouts manually.
With These Rules: Use the Aggregator EIP with idempotent repository and built-in completion strategies:
from("kafka:invoice.lineitems")
.routeId("invoice-agg-v1")
.aggregate(header("invoiceId"))
.completionSize(10)
.completionTimeout(1000)
.idempotent(true)
.aggregationRepository(redisRepo)
.to("direct:produce-invoice");
Instead of building custom threading and backpressure handling:
from("kafka:raw.events?groupId=processor")
.routeId("event-processor-v1")
.async()
.split(body()).streaming().parallelProcessing()
.to("direct:transform")
.to("kafka:processed.events");
<!-- Add to pom.xml -->
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-opentelemetry</artifactId>
</dependency>
Configure the rules in your Cursor workspace to get intelligent code completion for EIP patterns.
Organize routes by bounded context:
src/main/java/com/company/orders/integration/
├── routes/
│ ├── OrderSyncRoute.java
│ └── OrderAggregationRoute.java
├── processors/
│ └── OrderValidationProcessor.java
└── config/
└── OrderTopics.java
@Component
public class OrderSyncRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
// Global error handling
onException(Exception.class)
.handled(true)
.setHeader("fatalReason", simple("${exception.message}"))
.to("kafka:{{order.context}}.dlq");
// Main route with EIP patterns
from("kafka:orders.created?groupId=orders-sync")
.routeId("orders-sync-v1")
.validate(body().method("isValid"))
.circuitBreaker()
.choice()
.when(header("priority").isEqualTo("HIGH"))
.to("direct:priority-processing")
.otherwise()
.to("direct:standard-processing")
.end()
.onFallback()
.to("direct:fallback-processing")
.end();
}
}
The rules automatically configure OpenTelemetry tracing and OAuth2 security. You just need to add the configuration:
# application.yml
camel:
springboot:
tracing: true
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: ${OAUTH_ISSUER_URI}
Use the included Helm chart structure for cloud-native deployment with automatic scaling based on message throughput.
A typical enterprise integration team using these rules reports:
Your enterprise integrations become predictable, reliable, and maintainable. Instead of custom-coding every integration challenge, you apply proven patterns with consistent implementation standards that your entire team can understand and maintain.
Stop reinventing enterprise integration. Start building with patterns that scale.
You are an expert in: Apache Camel 4.x, Java 17+, Spring Boot 3, Kafka, OpenAPI, Kubernetes, OpenTelemetry, OAuth2, CI/CD (GitHub Actions), Docker, Helm, Istio, Debezium.
Key Principles
- API-first: every integration surface is defined in an OpenAPI contract that ships with the code.
- Prefer declarative, pattern-based routes using Camel Java DSL; fall back to XML/YAML only for heavily declarative config.
- Use a composable, event-driven architecture—Kafka topics are the canonical integration backbone.
- Cloud-agnostic: avoid vendor locks by packaging with Docker/Helm and externalising config.
- Zero-trust: every endpoint requires OAuth2/OIDC authentication; authorisation via fine-grained scopes.
- Fail fast: detect errors early, surface them through a single observability stack (OpenTelemetry → Prometheus/Grafana).
- Immutability & idempotency: design routes so that re-processing the same message produces the same outcome.
- Version everything: APIs, routes, schemas. Use semantic versioning and strict deprecation policies.
- Automate everything: lint, build, test, scan, deploy → GitHub Actions → Helm chart promotion.
Java (Primary Language)
- Use Java 17 records for simple, immutable DTOs.
- Route classes extend org.apache.camel.builder.RouteBuilder; name with *Route* suffix (e.g., OrderSyncRoute).
- Group routes by bounded context under package structure: com.company.<domain>.integration.<subsystem>.
- Prefer fluent Java DSL chaining; never embed business logic inside processors—delegate to service classes.
- Method references > lambdas when possible for clearer stack traces.
- Constants: public static final in a dedicated *Topics.java* or *Headers.java* utility.
- Enable compiler flags: -Werror -Xlint:all -parameters.
Error Handling and Validation
- Global onException() blocks first; specific → general ordering.
- Use Dead Letter Channel (DLC) per bounded context: kafka:{{context}}.dlq with full message + headers.
- Always attach exception message & stack-trace to Camel headers fatalReason, fatalStack.
- Retry policy: exponential back-off, max 5 attempts, jitter 10 %.
- Validate inbound messages upfront via Bean Validation (jakarta.validation) or JSON Schema.
- Early return pattern: stop() when payload invalid.
- Use CircuitBreaker EIP for downstream instability; configure half-open probe every 30 s.
Apache Camel Rules
- DSL selection: Java DSL for logic, YAML for simple declarative mappings, XML only for legacy compatibility.
- Start every route with a clear comment header describing purpose, inputs, outputs, and key EIPs.
- Always set routeId("<domain>-<verb>-v<major>").
- Mandatory integration patterns:
• Content-Based Router for format negotiation
• Message Filter for security/ACL enforcement
• Aggregator with timeout + completion size + idempotent repository (Redis) for fan-in scenarios
• Split/EIP streaming for large payloads; enable streaming() & parallelProcessing()
- Use Kafka component with transactional.id for exactly-once semantics when both in/out are Kafka.
- Transformations: prefer Camel AtlasMap component; avoid hand-written Processor unless absolutely required.
- Keep Processors stateless; inject needed beans via constructor for easier unit testing.
- Naming: kafka:orders.created → orders-created topic; kebab-case.
Testing
- Unit: camel-test-junit5 with AdviceWith to stub endpoints; 90 %+ line coverage.
- Contract: Pact V4 for HTTP; publish contracts to a Pact Broker.
- Integration: Testcontainers to spin up Kafka, Postgres, Keycloak, Debezium.
- CI: mvn verify must pass (unit + integration + static analysis) before merge.
Performance & Scalability
- Tune Camel thread pools via Spring Boot properties; prefer async() EIP to offload IO-bound steps.
- Enable backpressure: use Disruptor instead of SEDA for high-throughput routes.
- Kubernetes HPA scales on custom metric camel.route.exchanges.totalRate.
- Use Kafka partition key based on business correlation id for even load distribution.
Security
- All HTTP endpoints served through Spring Security OAuth2 Resource Server.
- Secrets via Kubernetes Secrets + sealed-secrets; never commit credentials.
- Enable TLS everywhere (Kafka mTLS, HTTPS).
Observability
- Enable camel-opentelemetry; propagate trace-id and span-id headers.
- Log struct-JSON to stdout; filtered by Loki.
- Set routePolicyFactory = MicrometerRoutePolicyFactory for automatic metrics.
CI/CD
- GitHub Actions workflow: mvn clean verify → docker build → helm lint → helm push.
- Use semantic-release for automated version bumps and changelog generation.
- Canary deployment via progressive delivery (Argo Rollouts).
Directory / Repository Layout (sample)
- src/main/java/com/company/**/routes/ – RouteBuilder classes
- src/main/java/com/company/**/processors/ – Lightweight processors
- src/main/resources/openapi/ – YAML contracts
- src/main/resources/mappings/ – AtlasMap ADM files
- charts/camel-integration/ – Helm chart
Common Pitfalls & Guardrails
- Do NOT block threads with Thread.sleep(); use ScheduledExecutorService or timer endpoint.
- Avoid global out-body mutations; always copy() exchange where mutation needed.
- Never swallow exceptions—always propagate to onException.
- Watch for object re-use across exchanges; keep everything immutable.
- Avoid megabyte-size headers (e.g., stack traces); truncate before DLQ.
Examples
```java
// 1. Content-Based Router with validation and DLC
from("kafka:orders.created?groupId=orders-sync")
.routeId("orders-sync-v1")
.validate(body().method("isValid"))
.choice()
.when(header("orderType").isEqualTo("EXPRESS"))
.to("direct:express")
.otherwise()
.to("direct:standard")
.end()
.onException(Exception.class)
.handled(true)
.to("kafka:orders.dlq?serializerClass=org.apache.kafka.common.serialization.StringSerializer")
;
```
```java
// 2. Aggregator with idempotent repository
from("kafka:invoice.lineitems")
.routeId("invoice-agg-v1")
.aggregate(header("invoiceId"))
.completionSize(10)
.completionTimeout(1000)
.idempotent(true)
.aggregationRepository(redisRepo)
.to("direct:produce-invoice")
;
```