archive2024

Workflow engines in Java: notes from using BPMN with Flowable and Camunda

When a BPMN workflow engine is worth it and when a status column plus a scheduler is enough. BPMN basics, embedding Flowable 7.1 in Spring Boot 3, the Camunda 7 and Camunda 8 situation as of late 2024, and the pitfalls I hit.

9 min read#dev#java#spring-boot#workflow

I had to choose a workflow engine again for a Spring Boot service with an approval process. The last time I did this, the choice was easy. This time Camunda changed a lot in 2024, so I collected my notes in one place. Versions are as of November 2024.

Do you need an engine at all?

Most “workflows” I see in business apps are a status column and a few rules:

create table purchase_request (
  id          bigint primary key,
  status      varchar(20) not null,  -- DRAFT, SUBMITTED, APPROVED, REJECTED, ORDERED
  updated_at  timestamp not null,
  version     int not null           -- optimistic locking
);

A service method checks the allowed transitions, and a @Scheduled job finds rows that waited too long. For this you do not need an engine. It is easy to test, easy to query, and every developer understands it.

A workflow engine starts to pay off when several of these are true at the same time:

  • The process runs for days or weeks, and must survive restarts and deployments.
  • People do steps: approve, review, fill in data. You need task lists, assignment to groups, and claims.
  • There are timers: escalate after two days, cancel after thirty, remind every morning.
  • Steps call other systems, and failed calls need retries and a place where an operator can see and restart them.
  • The process changes often, and business people want to see the flow as a diagram.
  • You need an audit trail of who did what and when.

If you only have one or two of these, I would still start with the state table. Moving from a state table to an engine later is work, but adding an engine you do not need is also work, every day.

BPMN in five elements

BPMN 2.0 is a standard notation with an XML format. Engines like Flowable and Camunda execute that XML. For most processes you need only a few elements:

  • Process definition: the deployed diagram. Each deployment of a changed diagram creates a new version with the same key.
  • User task: waits for a person. It has an assignee or candidate groups.
  • Service task: calls your code, for example a Spring bean.
  • Exclusive gateway: chooses one outgoing path based on a condition.
  • Timer event: a start timer, an intermediate wait, or a boundary timer on a task (“if this task is not done in 2 days, take this path”).

A process instance is one run of a definition, for example one purchase request. It carries process variables.

Flowable in Spring Boot 3

Flowable 7.0 (September 2023) was the first version for Spring Boot 3 and Jakarta EE, with Java 17 as baseline. The current version is 7.1.0, released in October 2024. On the API level it continues version 6, so old examples mostly still work after you change javax to jakarta. If you have not moved to Boot 3 yet, do that first.

<dependency>
  <groupId>org.flowable</groupId>
  <artifactId>flowable-spring-boot-starter-process</artifactId>
  <version>7.1.0</version>
</dependency>

This starter brings only the BPMN process engine. There is also flowable-spring-boot-starter, which brings the other engines too (CMMN, DMN and more). I prefer the smaller one.

The engine uses your normal DataSource and creates its ACT_* tables on startup. BPMN files in src/main/resources/processes/ with the suffix .bpmn20.xml or .bpmn are deployed automatically.

flowable:
  database-schema-update: true   # I set this to false in production and use migrations
  async-executor-activate: true  # needed for timers and async tasks

A small approval process

<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:flowable="http://flowable.org/bpmn"
             targetNamespace="http://example.com/processes">
  <process id="purchaseApproval" name="Purchase approval" isExecutable="true">
    <startEvent id="start"/>
    <sequenceFlow id="f1" sourceRef="start" targetRef="approve"/>

    <userTask id="approve" name="Approve purchase" flowable:candidateGroups="managers"/>
    <boundaryEvent id="approveTimeout" attachedToRef="approve" cancelActivity="true">
      <timerEventDefinition><timeDuration>P2D</timeDuration></timerEventDefinition>
    </boundaryEvent>
    <sequenceFlow id="f2" sourceRef="approve" targetRef="decision"/>
    <sequenceFlow id="f3" sourceRef="approveTimeout" targetRef="escalate"/>

    <exclusiveGateway id="decision"/>
    <sequenceFlow id="f4" sourceRef="decision" targetRef="placeOrder">
      <conditionExpression xsi:type="tFormalExpression">${approved}</conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="f5" sourceRef="decision" targetRef="rejected">
      <conditionExpression xsi:type="tFormalExpression">${!approved}</conditionExpression>
    </sequenceFlow>

    <serviceTask id="placeOrder" flowable:async="true"
                 flowable:delegateExpression="${placeOrderDelegate}"/>
    <serviceTask id="escalate" flowable:async="true"
                 flowable:delegateExpression="${escalateDelegate}"/>
    <sequenceFlow id="f6" sourceRef="placeOrder" targetRef="done"/>
    <sequenceFlow id="f7" sourceRef="escalate" targetRef="timedOut"/>

    <endEvent id="done"/>
    <endEvent id="rejected"/>
    <endEvent id="timedOut"/>
  </process>
</definitions>

I write small processes like this by hand. For bigger ones I use a modeler and keep the generated file in Git like any other source file. Review the diff; modelers sometimes change many lines for a small move.

The delegates are plain Spring beans:

@Component("placeOrderDelegate")
public class PlaceOrderDelegate implements JavaDelegate {

    private final OrderService orderService;

    public PlaceOrderDelegate(OrderService orderService) {
        this.orderService = orderService;
    }

    @Override
    public void execute(DelegateExecution execution) {
        long requestId = (Long) execution.getVariable("requestId");
        orderService.placeOrder(requestId);
    }
}

Starting a process and completing a task:

@Service
public class PurchaseWorkflow {

    private final RuntimeService runtimeService;
    private final TaskService taskService;

    public PurchaseWorkflow(RuntimeService runtimeService, TaskService taskService) {
        this.runtimeService = runtimeService;
        this.taskService = taskService;
    }

    public String start(long requestId) {
        return runtimeService.startProcessInstanceByKey(
                "purchaseApproval",
                "PR-" + requestId,                 // business key
                Map.of("requestId", requestId))
            .getId();
    }

    public List<Task> openApprovals() {
        return taskService.createTaskQuery()
                .processDefinitionKey("purchaseApproval")
                .taskCandidateGroup("managers")
                .orderByTaskCreateTime().asc()
                .list();
    }

    public void decide(String taskId, String userId, boolean approved) {
        taskService.claim(taskId, userId);
        taskService.complete(taskId, Map.of("approved", approved));
    }
}

Why flowable:async="true"

Without it, the service task runs in the same transaction as the call that completed the user task. If placeOrder throws, the user’s “approve” click fails and rolls back. With async="true", the engine commits the approval first and runs the service task as a job. When the job fails, the engine retries it (three times by default). After that it becomes a dead-letter job. You can find and restart those:

managementService.createDeadLetterJobQuery().list();
managementService.moveDeadLetterJobToExecutableJob(jobId, 3);

Put a small admin page or an alert on the dead-letter count. Otherwise nobody notices stuck instances.

The same rule applies to delegates that call external systems: make them idempotent. A job can run twice, for example when the node crashes after the HTTP call but before the commit.

Camunda 7 and Camunda 8 in late 2024

Camunda 7 is the classic Camunda engine. It is embedded in your Java app like Flowable (both come from the same Activiti code base), it has its own Spring Boot starter, and current versions support Spring Boot 3. The concepts above are almost the same, only the namespace and package names differ.

The important news is the end of life:

  • Camunda announced that Camunda 7 Community Edition reaches end of life in October 2025. The last CE release is planned as 7.24 on 14 October 2025. After that, no more CE releases, and the GitHub repository will be archived.
  • For the Enterprise Edition, the 7.22 release announcement (October 2024) talks about support until 2027, and extended support agreements until 2030.

Camunda 8 is a different product. The engine, Zeebe, runs as a separate cluster. Your application is a client that starts instances and registers job workers for service tasks over the network. Nothing is embedded, and you do not share a database transaction with the engine. This scales well, but it changes how you write and test code. It is not an upgrade of Camunda 7; it is a migration.

Licensing also changed. From Camunda 8.6 (released October 2024), the Self-Managed distribution needs a paid license for production use. Without a license it is for development and testing. Read the official licensing post yourself; I am not a lawyer and the details matter for your case.

So for a new embedded, open source engine in a Spring Boot app, I picked Flowable. If your company already pays for Camunda, Camunda 8 can be a good choice, but plan for the separate cluster. If you run Camunda 7 CE in production today, I would start planning now. October 2025 is less than a year away.

Pitfalls I hit

Versioning running instances

When you deploy a changed diagram, new instances use the new version. Running instances stay on the version they started with. That is usually what you want, but it means:

  • Old delegate bean names and variable names must keep working until the last old instance has finished. Do not rename a bean that an old version still calls.
  • A process that runs for months can block a cleanup for months.

Flowable has a ProcessMigrationService to move running instances to a new definition version, with a mapping for activities that changed. I have used it only for simple cases. Test the migration on a copy of production data first.

Business data does not belong in process variables

Variables are stored in engine tables, serialized, and copied into history. If you put a whole order with its lines into a variable, you get large rows, slow queries, and a second copy of your data that goes out of date. I keep only IDs and the values that gateways need (requestId, approved, an amount for a threshold). The real data stays in my own tables, and delegates load it by ID.

Avoid Java-serialized objects as variables. A class change can make old instances unreadable.

History tables grow

With the default history level, every finished task, activity and variable change is kept in the ACT_HI_* tables. That is the audit trail you wanted, but it grows without limit. Decide early how long to keep it. Flowable can clean up history itself:

flowable:
  enable-history-cleaning: true
  history-cleaning-after: 365d
  history-cleaning-cycle: '0 0 1 * * ?'   # every night at 01:00

If you have audit requirements, export what you need to your own tables before the cleanup deletes it. You can also lower flowable.history-level if you do not need full history.

Testing processes

I test processes at two levels:

  1. Delegates as normal unit tests, with mocked services. They are just Spring beans.
  2. The process flow with @SpringBootTest and a real engine on an in-memory or Testcontainers database. The test starts an instance, completes tasks, and checks where the instance is now.
@SpringBootTest
class PurchaseApprovalProcessTest {

    @Autowired RuntimeService runtimeService;
    @Autowired TaskService taskService;
    @MockBean OrderService orderService;

    @Test
    void approvedRequestEndsInDone() {
        var pi = runtimeService.startProcessInstanceByKey(
                "purchaseApproval", Map.of("requestId", 42L));

        Task task = taskService.createTaskQuery()
                .processInstanceId(pi.getId()).singleResult();
        assertThat(task.getTaskDefinitionKey()).isEqualTo("approve");

        taskService.complete(task.getId(), Map.of("approved", true));
        // placeOrder is async: run the jobs or wait for them here
    }
}

Async tasks and timers are the hard part, because they run in the job executor. In tests I either wait for the jobs with a helper and a timeout, or execute them directly with managementService.executeJob(jobId). For timers, I find the timer job with managementService.createTimerJobQuery(), move it with moveTimerToExecutableJob(jobId) and execute it. Then the test does not wait two days. For this I turn the async executor off in the test profile, so the background executor does not race with the test. Flowable also has a JUnit 5 extension (@FlowableTest with @Deployment) for tests without Spring. I have not used it much.

Moving running instances to a new process version is the one part I test by hand: on a staging database, before each release that changes a process.