Skip to main content

Service Orchestration in Aletyx Enterprise Build of Kogito and Drools 10.1.0-aletyx

Service orchestration coordinates interactions between multiple services to accomplish complex business objectives. Aletyx Enterprise Build of Kogito and Drools provides powerful orchestration capabilities through BPMN processes, enabling you to design, execute, and monitor multi-service workflows with visual process models, automated service invocations, and sophisticated error handling.

Understanding Service Orchestration

Service orchestration differs from service choreography by providing centralized coordination. An orchestrator process:
  • Defines the sequence of service calls explicitly
  • Manages state throughout the workflow
  • Handles errors and compensation centrally
  • Provides visibility into workflow progress
  • Enforces business rules and conditions
Orchestration vs Choreography: Diagram contrasting Orchestration and Choreography: in orchestration a central Orchestrator Process invokes Service A, B and C; in choreography the services coordinate by reacting to events Diagram contrasting Orchestration and Choreography: in orchestration a central Orchestrator Process invokes Service A, B and C; in choreography the services coordinate by reacting to events When to use orchestration:
  • Complex workflows with many conditional paths
  • Transactions requiring compensation patterns
  • Workflows needing human intervention
  • Processes requiring audit trails and monitoring
  • Long-running business processes
When to use choreography:
  • Loosely coupled event-driven systems
  • High scalability requirements
  • Services owned by different teams
  • Simple event notification patterns

Service Tasks in BPMN

The Service Task is the primary mechanism for invoking external services within BPMN processes.

Service Task Overview

Service Task Node Service Tasks enable:
  • REST API invocation: Call HTTP endpoints with custom headers and payloads
  • Java service calls: Invoke local Java methods directly
  • Custom work item handlers: Extend with specialized integration logic
  • Asynchronous execution: Execute long-running operations without blocking
  • Data transformation: Map process variables to service inputs and outputs
See BPMN Activities for detailed Service Task configuration.

Configuring REST Service Tasks

Example: Credit Bureau Integration Configure a Service Task to call an external credit bureau API: Process diagram: Flowchart of a REST service task example: Start, Validate Application, a 'Get Credit Score' service task, then a 'Score 700 or above?' decision; yes leads to Approve, no leads to Reject, then End Flowchart of a REST service task example: Start, Validate Application, a 'Get Credit Score' service task, then a 'Score 700 or above?' decision; yes leads to Approve, no leads to Reject, then End Service Task configuration:
  1. Task Type: Service Task
  2. Implementation: REST
  3. URL: https://credit-bureau.example.com/api/v1/scores
  4. Method: POST
  5. Content Type: application/json
Input mapping:
Output mapping: Map the response to process variables:
  • Response field score → Process variable creditScore
  • Response field reportId → Process variable creditReportId
Example REST call:
Response:

Java Service Task Implementation

Custom Java service class:
Service Task configuration in BPMN: Configure the task to call the Java method:
  1. Implementation: Java
  2. Interface: org.example.services.CreditService
  3. Operation: getCreditScore
  4. Parameters: Map process variables to method parameters
Input mapping:
  • Process variable applicantId → Parameter applicantId
  • Process variable ssn → Parameter ssn
Output mapping:
  • Method return value → Process variable creditScore

Asynchronous Service Tasks

For long-running operations, configure Service Tasks to execute asynchronously. Benefits:
  • Non-blocking: Process engine remains responsive
  • Scalability: Distribute work across job executors
  • Resilience: Automatic retry on transient failures
  • Resource management: Control concurrent task execution
Configuration:
  1. Select the Service Task
  2. Enable Is Async property
  3. Configure retry parameters (optional)
Process behavior with async: Sequence diagram of an asynchronous service task: the Process queues a Credit Check task with the Job Service and continues to the next safe point; the Job Service invokes the external Credit Bureau API, receives the credit score, signals task completion and the process resumes Sequence diagram of an asynchronous service task: the Process queues a Credit Check task with the Job Service and continues to the next safe point; the Job Service invokes the external Credit Bureau API, receives the credit score, signals task completion and the process resumes Job Service configuration (application.properties):

Orchestration Patterns

Sequential Service Orchestration

Call services in a defined sequence where each service depends on previous results. Use case: Loan Approval Workflow Flowchart of sequential service orchestration: Start, Validate Data, Check Credit Score, Verify Employment, Calculate DTI Ratio, Determine Eligibility, End Flowchart of sequential service orchestration: Start, Validate Data, Check Credit Score, Verify Employment, Calculate DTI Ratio, Determine Eligibility, End Implementation: Each Service Task executes sequentially, passing data through process variables. Example process variables flow:
  1. application (input) → Validate DatavalidationResult
  2. validationResultCheck Credit ScorecreditScore
  3. creditScoreVerify EmploymentemploymentVerified
  4. creditScore, employmentVerifiedCalculate DTIdtiRatio
  5. dtiRatio, creditScoreDetermine Eligibilityapproved

Parallel Service Orchestration

Invoke multiple independent services concurrently for performance. Use case: Multi-Bureau Credit Check Flowchart of parallel service orchestration: after Start a parallel gateway calls the Experian, Equifax and TransUnion APIs concurrently, then a join gateway leads to Aggregate Scores and End Flowchart of parallel service orchestration: after Start a parallel gateway calls the Experian, Equifax and TransUnion APIs concurrently, then a join gateway leads to Aggregate Scores and End Implementation:
  1. Parallel Gateway (fork): Splits process into parallel branches
  2. Service Tasks: Execute concurrently on separate threads
  3. Parallel Gateway (join): Waits for all branches to complete
  4. Aggregation Task: Combines results from parallel services
Performance benefit:
  • Sequential: 3 services × 2 seconds = 6 seconds
  • Parallel: Max(2, 2, 2) = 2 seconds

Conditional Service Routing

Route to different services based on runtime conditions. Use case: Product-Specific Pricing Flowchart of conditional service routing: after Start the process branches on product type to the Mortgage, Auto Loan or Personal Loan pricing service, then converges on Generate Quote Flowchart of conditional service routing: after Start the process branches on product type to the Mortgage, Auto Loan or Personal Loan pricing service, then converges on Generate Quote Implementation:
  1. Exclusive Gateway: Evaluates condition based on process variable
  2. Conditional flows: Each path has a condition expression
  3. Service Tasks: Different services on each path
  4. Converging Gateway: Paths rejoin after service execution
Gateway conditions:
  • Path to Mortgage: #{application.productType == 'MORTGAGE'}
  • Path to Auto Loan: #{application.productType == 'AUTO_LOAN'}
  • Path to Personal Loan: #{application.productType == 'PERSONAL_LOAN'}

Error Handling and Compensation

Handle service failures gracefully with error boundary events. Pattern: Service with Fallback Flowchart of error handling: Start, Primary Service, End; an error boundary event on the Primary Service diverts to a Fallback Service when an error occurs Flowchart of error handling: Start, Primary Service, End; an error boundary event on the Primary Service diverts to a Fallback Service when an error occurs Implementation:
  1. Attach Error Boundary Event to Service Task
  2. Configure error code to catch (e.g., HTTP 500, timeout)
  3. Define error handling path
  4. Optional: retry logic before fallback
Example boundary event configuration:
  • Error Code: 500
  • Error Name: ServiceUnavailable
  • Handler Path: Route to fallback service or compensation
Compensation pattern: Flowchart of compensation handling: Reserve Inventory then Charge Payment; if an error occurs, compensation runs Release Inventory and Cancel Order Flowchart of compensation handling: Reserve Inventory then Charge Payment; if an error occurs, compensation runs Release Inventory and Cancel Order

Saga Pattern with Orchestration

Implement distributed transactions using compensation. Use case: Order Fulfillment Saga Flowchart of an orchestrated saga: Start Order, Reserve Inventory, Charge Payment, Ship Order, End Success; on failure, compensating steps Refund Payment, Release Inventory and Cancel Order lead to End Cancelled Flowchart of an orchestrated saga: Start Order, Reserve Inventory, Charge Payment, Ship Order, End Success; on failure, compensating steps Refund Payment, Release Inventory and Cancel Order lead to End Cancelled Implementation steps:
  1. Forward path: Define normal execution sequence
  2. Compensation handlers: Attach to each Service Task
  3. Error boundaries: Catch failures and trigger compensation
  4. Compensation logic: Undo completed steps in reverse order
Compensation example: If payment fails after inventory reserved:
  1. Error boundary event catches payment failure
  2. Process triggers compensation for “Reserve Inventory” task
  3. Compensation calls “Release Inventory” service
  4. Process transitions to cancellation path

Data Transformation and Mapping

Input Mapping

Transform process variables into service request format. Expression examples:
Complex JSON construction:

Output Mapping

Extract data from service responses and store in process variables. JSON Path extraction:
  • $.score → Extract score field from root
  • $.applicant.creditHistory.accounts → Extract nested array
  • $..transactionId → Extract all transactionId fields (recursive)
Mapping strategies:
  1. Direct mapping: Response field → Process variable
  2. Transformation: Apply expression to response data
  3. Conditional mapping: Map different fields based on conditions
  4. Collection mapping: Iterate over response arrays
Example output mapping: Service returns:
Mappings:
  • $.scoreResult.scorecreditScore (Integer)
  • $.scoreResult.tiercreditTier (String)
  • $.reportIdcreditReportId (String)

Data Validation

Validate service responses before continuing process execution. Validation patterns:
  1. Gateway after service: Check response validity
  2. Script task: Perform complex validation logic
  3. Business rule task: Validate using decision rules
  4. Boundary error event: Handle invalid responses
Example validation gateway:
If validation fails, route to error handling path.

Service Registry and Discovery

Static Service Configuration

Configure service endpoints in application properties. application.properties:
Reference in Service Task:

Dynamic Service Discovery

Integrate with service registries for dynamic endpoint resolution. Kubernetes service discovery:
Service Task URL:
Kubernetes DNS resolves service name to active pod IPs automatically.

Monitoring and Observability

Process Instance Tracking

Monitor orchestration execution in real-time. Key metrics:
  • Process duration: Time from start to completion
  • Service task latency: Time per service invocation
  • Active instances: Currently executing processes
  • Completion rate: Successful vs failed instances
  • Bottleneck identification: Tasks with longest wait times
Process dashboard queries:

Distributed Tracing

Trace requests across service boundaries. OpenTelemetry integration:
Trace visualization:

Error Logging and Alerting

Capture and alert on orchestration failures. Structured logging:
Alerting rules (Prometheus):

Best Practices

Process Design

  1. Keep processes focused: One process per business capability
  2. Limit process complexity: Break large processes into sub-processes
  3. Handle errors explicitly: Define error paths for all service tasks
  4. Use meaningful names: Clear task and variable names
  5. Document process logic: Add annotations explaining business rules

Service Integration

  1. Design for failure: Assume services will fail
  2. Implement timeouts: Prevent indefinite waiting
  3. Use circuit breakers: Protect against cascading failures
  4. Validate responses: Check service outputs before continuing
  5. Version service contracts: Handle backward compatibility

Performance Optimization

  1. Parallelize independent tasks: Use parallel gateways
  2. Minimize data transfer: Only pass necessary variables
  3. Use async for long operations: Prevent process engine blocking
  4. Cache frequent lookups: Store static reference data
  5. Monitor execution times: Identify slow services

Security Considerations

  1. Secure credentials: Use secrets management for API keys
  2. Encrypt sensitive data: Protect PII in process variables
  3. Validate inputs: Sanitize data before service calls
  4. Audit service access: Log all external service invocations
  5. Use mutual TLS: Authenticate both client and server

Testing Strategy

  1. Unit test service adapters: Test service integration code
  2. Mock external services: Use WireMock or similar for testing
  3. Integration test processes: Validate full orchestration flows
  4. Performance test under load: Verify scalability
  5. Chaos test error handling: Simulate service failures

Deployment Architectures

Embedded Process Engine

Deploy process engine within the application. Characteristics:
  • Single deployable unit: Application and engine together
  • Low latency: No network calls to separate engine
  • Simple deployment: One container/application
  • Resource sharing: Process engine shares application resources
Use cases:
  • Microservices with embedded workflows
  • Lightweight orchestration needs
  • Fast startup requirements

Centralized Process Engine

Deploy process engine as separate service. Characteristics:
  • Multiple applications: Many apps interact with one engine
  • Centralized monitoring: Single view of all processes
  • Shared infrastructure: Engine managed independently
  • Horizontal scaling: Scale engine separately
Use cases:
  • Enterprise-wide orchestration
  • Complex governance requirements
  • Multiple applications sharing workflows

Hybrid Architecture

Combine embedded and centralized approaches. Strategy:
  • Embedded engines for domain-specific workflows
  • Centralized engine for cross-domain orchestration
  • Event-based integration between engines
Benefits:
  • Autonomy: Teams control their workflows
  • Coordination: Central orchestration when needed
  • Scalability: Scale components independently

Next Steps