Building a Lightweight Workflow Engine for Dynamic Approvals with Java 21 and Spring Boot
This article details the design and implementation of a lightweight workflow engine using Java 21, Spring Boot, and MySQL, covering JSON-based process definitions, versioning, dynamic assignee resolution, multi-approval modes with concurrency control, condition evaluation, node transitions, rejection/resubmission patterns, timeout reminders, and event-driven integration with business systems.
Reading font

Introduction: Why a Workflow Engine Is Needed
When building an enterprise approval system with Spring Boot, a common requirement is that administrators can configure approval processes in the backend without developers modifying code for every rule change. For example, leave requests under one day need a direct manager's approval; over one day requires a department manager; over three days adds HR. Purchase amounts under 5,000 go to a department manager; 5,000–100,000 adds finance; over 100,000 adds the general manager. These rules vary by company, department, and time. Hard‑coding them with if‑else chains in services leads to an unmaintainable system. Additional complexities include multi‑person countersign (ALL), any‑one approval (ANY), threshold voting, rejection with resubmission, delegation, timeout reminders, and ensuring that process changes do not affect already‑running instances. The solution is a lightweight workflow engine that executes processes based on configuration.
1. Why Simple Approval Table Designs Fail
Early implementations often add approval fields directly to business tables:
CREATE TABLE leave_application (</code><code> id BIGINT PRIMARY KEY,</code><code> applicant_id BIGINT NOT NULL,</code><code> leave_days DECIMAL(6,2) NOT NULL,</code><code> reason VARCHAR(500),</code><code> approver_id BIGINT,</code><code> status VARCHAR(32) NOT NULL,</code><code> created_at DATETIME(3) NOT NULL</code><code>);When multi‑level approval is needed, developers add first_approver_id, second_approver_id, etc. Every new level or parallel approver forces schema changes. The core problem is embedding the approval flow into the business table. The business data (applicant, dates, reason) should be separate from the workflow that routes the request. The article proposes five core models:
ProcessDefinition — Process definition, e.g., leave approval, purchase approval
ProcessVersion — Published concrete process version
ProcessInstance — An actual launched approval process
NodeInstance — One execution of an approval node
ApprovalTask — A todo task assigned to a specific approver
When an employee submits a purchase request, the purchase system creates the order, the workflow engine creates a process instance, and generates approval tasks based on the process configuration. The business system only needs to know whether the process is finished and the final result. Adding a new approval type then only requires configuring a new process, not rewriting the approval module.
2. Using JSON to Define Approval Processes, Decoupling Rules from Java Code
Instead of Java if‑else chains:
if (amount.compareTo(new BigDecimal("100000")) >= 0) {</code><code> createManagerTask();</code><code> createFinanceTask();</code><code> createGeneralManagerTask();</code><code>} else if (amount.compareTo(new BigDecimal("5000")) >= 0) {</code><code> createManagerTask();</code><code> createFinanceTask();</code><code>} else {</code><code> createManagerTask();</code><code>}The article defines a JSON process definition for purchase approval:
{</code><code> "processKey": "purchase_approval",</code><code> "version": 1,</code><code> "startNode": "manager",</code><code> "nodes": [</code><code> {</code><code> "id": "manager",</code><code> "name": "部门经理审批",</code><code> "type": "APPROVAL",</code><code> "approvalMode": "ANY",</code><code> "assignee": {</code><code> "type": "DEPARTMENT_MANAGER"</code><code> },</code><code> "transitions": [</code><code> {</code><code> "target": "finance",</code><code> "condition": {</code><code> "field": "amount",</code><code> "operator": "GTE",</code><code> "value": 5000</code><code> }</code><code> },</code><code> {</code><code> "target": "end",</code><code> "default": true</code><code> }</code><code> ]</code><code> },</code><code> {</code><code> "id": "finance",</code><code> "name": "财务会签",</code><code> "type": "APPROVAL",</code><code> "approvalMode": "ALL",</code><code> "assignee": {</code><code> "type": "ROLE",</code><code> "value": "FINANCE_APPROVER"</code><code> },</code><code> "transitions": [</code><code> {</code><code> "target": "general_manager",</code><code> "condition": {</code><code> "field": "amount",</code><code> "operator": "GTE",</code><code> "value": 100000</code><code> }</code><code> },</code><code> {</code><code> "target": "end",</code><code> "default": true</code><code> }</code><code> ]</code><code> },</code><code> {</code><code> "id": "general_manager",</code><code> "name": "总经理审批",</code><code> "type": "APPROVAL",</code><code> "approvalMode": "ANY",</code><code> "assignee": {</code><code> "type": "ROLE",</code><code> "value": "GENERAL_MANAGER"</code><code> },</code><code> "transitions": [</code><code> {</code><code> "target": "end",</code><code> "default": true</code><code> }</code><code> ]</code><code> },</code><code> {</code><code> "id": "end",</code><code> "type": "END"</code><code> }</code><code> ]</code><code>}This JSON describes a simple process graph. The Java backend no longer cares whether it is purchase or leave approval; it only parses node configuration, executes assignee rules, evaluates branch conditions, and moves to the next node. If an admin changes the finance threshold from 5,000 to 8,000, they publish a new process version without touching Java code. However, process definitions must be validated before publishing: check for duplicate node IDs, existence of target nodes, uniqueness of default branches, validity of assignee rules, and reachability of the end node from all normal paths. The first version of the lightweight engine explicitly forbids cycles and arbitrary parallel branches to avoid premature complexity in execution semantics.
3. Process Configuration Can Change, but Running Instances Must Not
This is a commonly overlooked issue in dynamic approval systems. Suppose purchase process v1 requires finance approval for amounts >5,000. An employee submits an 8,000 purchase order; the department manager approves, and it waits for finance. The next day the admin changes the rule to >10,000. Should the in‑flight order skip finance? Usually not, because the request was started under v1. If every node execution reads the latest config, running processes would change mid‑flight.
Therefore, process definitions and process versions must be stored separately:
CREATE TABLE workflow_definition (</code><code> id BIGINT PRIMARY KEY AUTO_INCREMENT,</code><code> tenant_id BIGINT NOT NULL,</code><code> process_key VARCHAR(64) NOT NULL,</code><code> process_name VARCHAR(128) NOT NULL,</code><code> current_version INT NULL,</code><code> enabled TINYINT NOT NULL DEFAULT 1,</code><code></code><code> UNIQUE KEY uk_process (tenant_id, process_key)</code><code>);Concrete versions are stored in a separate table:
CREATE TABLE workflow_version (</code><code> id BIGINT PRIMARY KEY AUTO_INCREMENT,</code><code> definition_id BIGINT NOT NULL,</code><code> version_no INT NOT NULL,</code><code> definition_json JSON NOT NULL,</code><code> status VARCHAR(20) NOT NULL,</code><code> created_by BIGINT NOT NULL,</code><code> published_at DATETIME(3),</code><code></code><code> UNIQUE KEY uk_workflow_version (definition_id, version_no)</code><code>);When starting an approval, the process instance must bind to a published version:
CREATE TABLE workflow_instance (</code><code> id BIGINT PRIMARY KEY AUTO_INCREMENT,</code><code> tenant_id BIGINT NOT NULL,</code><code> workflow_version_id BIGINT NOT NULL,</code><code> business_type VARCHAR(64) NOT NULL,</code><code> business_id VARCHAR(128) NOT NULL,</code><code> applicant_id BIGINT NOT NULL,</code><code></code><code> current_node_instance_id BIGINT NULL,</code><code> variables JSON NOT NULL,</code><code> status VARCHAR(32) NOT NULL,</code><code></code><code> started_at DATETIME(3) NOT NULL,</code><code> finished_at DATETIME(3),</code><code></code><code> INDEX idx_business (tenant_id, business_type, business_id)</code><code>);The variables column holds the business variables for this run, e.g.:
{</code><code> "amount": 8000,</code><code> "departmentId": 1001,</code><code> "purchaseType": "OFFICE_EQUIPMENT",</code><code> "applicantId": 20001</code><code>}These variables must come from a trusted business service, not the frontend. Otherwise a user could change an 80,000 purchase amount to 800 and bypass finance approval. Important fields that determine the approval path should be frozen at process start, or only modifiable through an authorized resubmit operation. Thus, even after v6 is published, instances started on v1 continue executing v1. Publishing a new version is a configuration change, not an operation that rewrites historical approval records.
4. Dynamic Assignees: Direct Manager, Role, Designated User — Not Hard‑coded
Different enterprises have vastly different assignee requirements: direct manager, department head, all users with a finance role, or applicant‑selected from a pool. Hard‑coding these in one service leads to if‑else sprawl. The article uses Java interfaces and the Strategy pattern to create independent resolvers for each assignee rule.
Assignee type enum:
public enum AssigneeType {</code><code> FIXED_USER,</code><code> ROLE,</code><code> DIRECT_MANAGER,</code><code> DEPARTMENT_MANAGER,</code><code> APPLICANT_SELECTED</code><code>}Assignee rule record:
public record AssigneeRule(</code><code> AssigneeType type,</code><code> String value</code><code>) {}Unified resolver interface:
public interface AssigneeResolver {</code><code> AssigneeType supports();</code><code> List<Long> resolve(AssigneeRule rule, WorkflowContext context);</code><code>}Department manager resolver example:
@Component</code><code>public class DepartmentManagerResolver implements AssigneeResolver {</code><code> private final OrganizationService organizationService;</code><code> public DepartmentManagerResolver(OrganizationService organizationService) {</code><code> this.organizationService = organizationService;</code><code> }</code><code> @Override</code><code> public AssigneeType supports() {</code><code> return AssigneeType.DEPARTMENT_MANAGER;</code><code> }</code><code> @Override</code><code> public List<Long> resolve(AssigneeRule rule, WorkflowContext context) {</code><code> return organizationService.findDepartmentManagers(</code><code> context.tenantId(),</code><code> context.departmentId()</code><code> );</code><code> }</code><code>}Role‑based resolver:
@Component</code><code>public class RoleAssigneeResolver implements AssigneeResolver {</code><code> private final UserRoleService userRoleService;</code><code> public RoleAssigneeResolver(UserRoleService userRoleService) {</code><code> this.userRoleService = userRoleService;</code><code> }</code><code> @Override</code><code> public AssigneeType supports() {</code><code> return AssigneeType.ROLE;</code><code> }</code><code> @Override</code><code> public List<Long> resolve(AssigneeRule rule, WorkflowContext context) {</code><code> return userRoleService.findActiveUsersByRole(</code><code> context.tenantId(),</code><code> rule.value()</code><code> );</code><code> }</code><code>}Spring injects all implementations into a unified service:
@Service</code><code>public class AssigneeResolveService {</code><code> private final Map<AssigneeType, AssigneeResolver> resolvers;</code><code> public AssigneeResolveService(List<AssigneeResolver> resolverList) {</code><code> this.resolvers = resolverList.stream()</code><code> .collect(Collectors.toUnmodifiableMap(</code><code> AssigneeResolver::supports,</code><code> Function.identity()</code><code> ));</code><code> }</code><code> public List<Long> resolve(AssigneeRule rule, WorkflowContext context) {</code><code> AssigneeResolver resolver = resolvers.get(rule.type());</code><code> if (resolver == null) {</code><code> throw new IllegalArgumentException("Unsupported assignee type: " + rule.type());</code><code> }</code><code> List<Long> users = resolver.resolve(rule, context)</code><code> .stream()</code><code> .filter(Objects::nonNull)</code><code> .distinct()</code><code> .toList();</code><code> if (users.isEmpty()) {</code><code> throw new IllegalStateException("No valid approver found for current node");</code><code> }</code><code> return users;</code><code> }</code><code>}Adding a new assignee type (e.g., regional manager, project manager) only requires a new resolver; the core engine stays untouched.
A subtle issue: if an employee changes departments during approval, should the next node use the new department or the one at submission? The article recommends freezing the applicant's department at process start, while resolving the specific department manager at node activation. Once tasks are created, the assigned approvers are persisted and do not auto‑update with org changes. If an approver leaves or is disabled, handle it via explicit delegation or admin reassignment, not silent background changes.
5. Multi‑person Countersign (ALL) and Any‑one (ANY): The Real Challenge Is Concurrency
A finance node may need three finance staff to approve. All must agree (countersign/ALL) or any one agrees (ANY). Threshold voting (e.g., 3 of 5, or 80%) is also supported.
public enum ApprovalMode {</code><code> ALL, // all approvers must agree</code><code> ANY, // any one approver agrees</code><code> THRESHOLD // reach specified count</code><code>}To support multi‑person approval, each approver gets a separate task row, not a single approver ID on the instance.
Node instance table:
CREATE TABLE workflow_node_instance (</code><code> id BIGINT PRIMARY KEY AUTO_INCREMENT,</code><code> instance_id BIGINT NOT NULL,</code><code> node_key VARCHAR(64) NOT NULL,</code><code> execution_no INT NOT NULL,</code><code> approval_mode VARCHAR(20) NOT NULL,</code><code> required_approvals INT NOT NULL,</code><code> status VARCHAR(20) NOT NULL,</code><code></code><code> activated_at DATETIME(3) NOT NULL,</code><code> finished_at DATETIME(3),</code><code></code><code> UNIQUE KEY uk_node_execution (instance_id, execution_no)</code><code>);Task table:
CREATE TABLE workflow_task (</code><code> id BIGINT PRIMARY KEY AUTO_INCREMENT,</code><code> tenant_id BIGINT NOT NULL,</code><code> instance_id BIGINT NOT NULL,</code><code> node_instance_id BIGINT NOT NULL,</code><code> assignee_id BIGINT NOT NULL,</code><code></code><code> status VARCHAR(20) NOT NULL,</code><code> comment VARCHAR(1000),</code><code></code><code> created_at DATETIME(3) NOT NULL,</code><code> completed_at DATETIME(3),</code><code></code><code> UNIQUE KEY uk_node_assignee (node_instance_id, assignee_id),</code><code> INDEX idx_user_pending (tenant_id, assignee_id, status, created_at),</code><code> INDEX idx_node_task (node_instance_id, status)</code><code>);The required_approvals on the node instance is computed at activation time. For five approvers:
ALL (countersign) → 5
ANY → 1
THRESHOLD 3 → 3
80% → 4
Converting all modes to a required‑count threshold simplifies node state calculation. A VoteSummary record tracks counts:
public record VoteSummary(</code><code> int approved,</code><code> int rejected,</code><code> int pending,</code><code> int required</code><code>) {</code><code> public boolean passed() {</code><code> return approved >= required;</code><code> }</code><code> public boolean impossibleToPass() {</code><code> return approved + pending < required;</code><code> }</code><code>}Business rule: reaching the required approvals passes the node; if even all remaining pending approvals cannot meet the threshold, the node fails. A specific veto power for a designated approver should be a separate veto strategy, not mixed into the vote count.
Concurrency is the real technical difficulty. Two finance approvers A and B click "approve" simultaneously; requests hit different Spring Boot instances. If each thread completes its task and independently queries other approvers' status, duplicate node advancement or permanent stall can occur.
The article recommends using the process instance as the unified concurrency control boundary. The ApprovalService.approve() method locks the process instance row first:
@Service</code><code>public class ApprovalService {</code><code> private final InstanceMapper instanceMapper;</code><code> private final NodeInstanceMapper nodeMapper;</code><code> private final TaskMapper taskMapper;</code><code> private final WorkflowEngine workflowEngine;</code><code> // constructor omitted</code><code> @Transactional</code><code> public void approve(long tenantId, long instanceId, long taskId, long operatorId, String comment) {</code><code> WorkflowInstance instance = instanceMapper.lockById(tenantId, instanceId);</code><code> if (instance == null) throw new IllegalArgumentException("Process not found");</code><code> ApprovalTask task = taskMapper.lockById(tenantId, instanceId, taskId);</code><code> if (task == null || task.getAssigneeId() != operatorId)</code><code> throw new SecurityException("Not authorized for this task");</code><code> if (task.getStatus() == TaskStatus.APPROVED) return;</code><code> if (instance.getStatus() != InstanceStatus.RUNNING)</code><code> throw new IllegalStateException("Process already finished");</code><code> if (!Objects.equals(instance.getCurrentNodeInstanceId(), task.getNodeInstanceId()))</code><code> throw new IllegalStateException("Current task already invalid");</code><code> int updated = taskMapper.approveIfPending(tenantId, taskId, operatorId, comment);</code><code> if (updated != 1) throw new IllegalStateException("Task already processed or invalid");</code><code> NodeInstance node = nodeMapper.findById(task.getNodeInstanceId());</code><code> VoteSummary votes = taskMapper.summarizeCurrent(node.getId(), node.getRequiredApprovals());</code><code> if (votes.passed()) {</code><code> workflowEngine.completeNode(instance, node);</code><code> }</code><code> }</code><code>}The instanceMapper.lockById() uses a database row lock:
SELECT * FROM workflow_instance</code><code>WHERE tenant_id = #{tenantId} AND id = #{instanceId}</code><code>FOR UPDATE;Task update also includes status and assignee conditions:
UPDATE workflow_task</code><code>SET status = 'APPROVED',</code><code> comment = #{comment},</code><code> completed_at = NOW(3)</code><code>WHERE tenant_id = #{tenantId}</code><code> AND id = #{taskId}</code><code> AND assignee_id = #{operatorId}</code><code> AND status = 'PENDING';Vote summarization must read committed data plus the current transaction's changes. Using READ COMMITTED isolation or current reads under the process lock avoids stale snapshots. All approval actions (approve, reject, withdraw, delegate, node advance) must follow the same lock ordering. This design serializes approvals for the same process via short DB transactions; different processes still run concurrently. No Redis distributed lock is needed.
6. Conditional Branching: Do Not Allow Arbitrary Java Expressions
Dynamic approval needs to pick the next node based on business variables, e.g., amount >= 5000 → finance, leaveDays > 3 → HR, contractType = SALES → sales lead. Some teams let admins write SpEL, JavaScript, or other scripts executed on the server. This is flexible but raises security and maintenance concerns: unrestricted expressions can access objects beyond business variables or call unintended methods.
The article prefers a restricted condition expression model:
public enum ConditionOperator {</code><code> EQ, NE, GT, GTE, LT, LTE</code><code>}Condition record:
public record WorkflowCondition(</code><code> String field,</code><code> ConditionOperator operator,</code><code> Object value</code><code>) {}Core evaluator:
@Component</code><code>public class ConditionEvaluator {</code><code> public boolean evaluate(WorkflowCondition condition, Map<String, Object> variables) {</code><code> if (!variables.containsKey(condition.field())) {</code><code> throw new IllegalArgumentException("Missing process variable: " + condition.field());</code><code> }</code><code> Object actual = variables.get(condition.field());</code><code> Object expected = condition.value();</code><code> return switch (condition.operator()) {</code><code> case EQ -> equalValue(actual, expected);</code><code> case NE -> !equalValue(actual, expected);</code><code> case GT -> compareNumber(actual, expected) > 0;</code><code> case GTE -> compareNumber(actual, expected) >= 0;</code><code> case LT -> compareNumber(actual, expected) < 0;</code><code> case LTE -> compareNumber(actual, expected) <= 0;</code><code> };</code><code> }</code><code> private boolean equalValue(Object left, Object right) {</code><code> if (left instanceof Number && right instanceof Number) {</code><code> return compareNumber(left, right) == 0;</code><code> }</code><code> return Objects.equals(left, right);</code><code> }</code><code> private int compareNumber(Object left, Object right) {</code><code> if (!(left instanceof Number) || !(right instanceof Number)) {</code><code> throw new IllegalArgumentException("Comparison only supports numeric types");</code><code> }</code><code> BigDecimal a = new BigDecimal(left.toString());</code><code> BigDecimal b = new BigDecimal(right.toString());</code><code> return a.compareTo(b);</code><code> }</code><code>}Benefits: (1) admins only use platform‑supported fields and operators, no arbitrary code execution; (2) rules map directly to a visual config UI — dropdown for field, operator, value input. Later, AND/OR condition groups can be added with nesting depth limits. Example composite condition:
{</code><code> "logic": "AND",</code><code> "conditions": [</code><code> { "field": "amount", "operator": "GTE", "value": 50000 },</code><code> { "field": "purchaseType", "operator": "EQ", "value": "EQUIPMENT" }</code><code> ]</code><code>}Production must define allowed variables and types per process. Amount fields should use BigDecimal for precision, not float. Branch matching order must be deterministic: evaluate non‑default transitions in configured order, take the first match; if none match, use the default transition. This guarantees predictable execution even when multiple conditions are true.
7. How the Engine Auto‑Advances to the Next Node
When a node meets its pass condition, the engine must: end the current node, cancel remaining tasks, compute the next node, resolve new assignees, and create the next batch of tasks. This logic belongs in the engine, not the controller.
Node definition record:
public record WorkflowNode(</code><code> String id,</code><code> String name,</code><code> NodeType type,</code><code> ApprovalMode approvalMode,</code><code> Integer requiredApprovals,</code><code> AssigneeRule assignee,</code><code> List<NodeTransition> transitions</code><code>) {}Transition record:
public record NodeTransition(</code><code> String target,</code><code> WorkflowCondition condition,</code><code> boolean defaultTransition</code><code>) {}Transition resolver:
@Component</code><code>public class TransitionResolver {</code><code> private final ConditionEvaluator evaluator;</code><code> public TransitionResolver(ConditionEvaluator evaluator) {</code><code> this.evaluator = evaluator;</code><code> }</code><code> public String next(WorkflowNode node, Map<String, Object> variables) {</code><code> String defaultTarget = null;</code><code> for (NodeTransition transition : node.transitions()) {</code><code> if (transition.defaultTransition()) {</code><code> defaultTarget = transition.target();</code><code> continue;</code><code> }</code><code> if (evaluator.evaluate(transition.condition(), variables)) {</code><code> return transition.target();</code><code> }</code><code> }</code><code> if (defaultTarget != null) return defaultTarget;</code><code> throw new IllegalStateException("No executable next node found");</code><code> }</code><code>}Engine's node completion logic (runs inside the same transaction as the approval action):
@Service</code><code>public class WorkflowEngine {</code><code> // constructor and helpers omitted</code><code> @Transactional(propagation = Propagation.MANDATORY)</code><code> public void completeNode(WorkflowInstance instance, NodeInstance nodeInstance) {</code><code> WorkflowDefinition definition = definitionLoader.loadVersion(instance.getWorkflowVersionId());</code><code> WorkflowNode currentNode = definition.getNode(nodeInstance.getNodeKey());</code><code> String nextNodeKey = transitionResolver.next(currentNode, instance.getVariables());</code><code> WorkflowNode nextNode = definition.getNode(nextNodeKey);</code><code> if (nodeMapper.completeIfActive(nodeInstance.getId()) != 1)</code><code> throw new IllegalStateException("Node already processed");</code><code> taskMapper.cancelPending(nodeInstance.getId());</code><code> if (nextNode.type() == NodeType.END) {</code><code> instanceMapper.finishApproved(instance.getId());</code><code> outboxMapper.insert(WorkflowCompletedEvent.approved(instance));</code><code> return;</code><code> }</code><code> activateNode(instance, nextNode);</code><code> }</code><code>}activateNode()resolves assignees, computes the required‑approvals threshold, creates a new node instance, bulk‑inserts tasks, and updates the process instance's current node pointer. All these DB operations must run in the same transaction as the node completion. If the next node has no valid assignees or task creation fails, the whole transaction rolls back; production can add an exception‑suspended state for admin recovery. Notifications (SMS, WeCom, in‑app) must not block the core transaction. The reliable pattern: write notification events to an Outbox table; after commit, an async publisher sends them. Notification retries must not roll back completed approvals.
8. Reject, Return‑for‑Revision, Withdraw, Delegate — Not Just Status Changes
After launch, products quickly add exceptional flows: finance returns a purchase request for missing attachments; an approver delegates while traveling; an applicant withdraws before final approval. These look like status changes but have distinct semantics:
Reject — process ends, result = not approved
Return‑for‑revision — process pauses, waits for applicant to modify and resubmit
Withdraw — applicant terminates the process per business rules
Delegate — reassign current pending task to another authorized person
Resubmit — create a new round of node execution, re‑enter approval
The key is distinguishing the process definition's node from the node execution instance. Example: a process goes department manager → finance → general manager. Finance returns for revision; applicant changes amount and resubmits. The definition node ID is still manager, but this is the second execution. If resubmit merely flipped the original task from APPROVED back to PENDING, the original approval record would be overwritten. Instead, create a new node instance:
First execution:</code><code>Department manager node instance 101: approved</code><code>Finance node instance 102: returned</code><code>Resubmit:</code><code>Department manager node instance 103: pendingOriginal instances 101 and 102 remain intact; the new round has independent node instances and task IDs. Late requests on old tasks are rejected because the current node instance ID no longer matches.
For variable‑changing resubmits, the article recommends restarting from the start node of the original process version, not allowing arbitrary jumps to historical nodes. This reduces complexity and prevents bypassing required steps (e.g., changing amount to skip finance).
Independent audit logs are essential:
CREATE TABLE workflow_action_log (</code><code> id BIGINT PRIMARY KEY AUTO_INCREMENT,</code><code> tenant_id BIGINT NOT NULL,</code><code> instance_id BIGINT NOT NULL,</code><code> node_instance_id BIGINT,</code><code> task_id BIGINT,</code><code> operator_id BIGINT NOT NULL,</code><code></code><code> action VARCHAR(32) NOT NULL,</code><code> detail JSON,</code><code> created_at DATETIME(3) NOT NULL,</code><code></code><code> INDEX idx_instance_history (instance_id, created_at, id)</code><code>);Delegation records original approver, new approver, operator, and reason, committed atomically with the task ownership change. Admins viewing approval details see the full operation history, not just the current assignee.
9. Timeout Reminders, Auto‑Escalation, and Business System Integration
Enterprises often require: remind after 24h pending, escalate to superior after 48h. Add reminder columns to the task table:
ALTER TABLE workflow_task</code><code>ADD COLUMN next_remind_at DATETIME(3),</code><code>ADD COLUMN remind_count INT NOT NULL DEFAULT 0,</code><code>ADD COLUMN due_at DATETIME(3),</code><code>ADD INDEX idx_remind (status, next_remind_at);A background job scans pending tasks due for reminder:
SELECT id, tenant_id, instance_id</code><code>FROM workflow_task</code><code>WHERE status = 'PENDING'</code><code> AND next_remind_at <= NOW(3)</code><code>ORDER BY next_remind_at, id</code><code>LIMIT 200;Before sending, re‑verify the task is still pending (the approver may have acted after the scan). In multi‑instance deployments, use the process instance lock to atomically increment the reminder count and write the notification event. Use task ID + reminder round as idempotency key to avoid duplicate reminders.
For auto‑escalation, the system can reassign or delegate per explicit config, but the article advises against default auto‑approve on timeout, especially for purchasing, payments, contracts — auto‑approve could bypass internal controls.
After full approval, the originating business system must be notified. Do not embed business logic in the engine:
if ("PURCHASE".equals(businessType)) {</code><code> purchaseService.approve(businessId);</code><code>} else if ("LEAVE".equals(businessType)) {</code><code> leaveService.approve(businessId);</code><code>} else if ("EXPENSE".equals(businessType)) {</code><code> expenseService.approve(businessId);</code><code>}This couples the engine to every business module. Instead, publish a unified completion event:
public record WorkflowCompletedEvent(</code><code> String eventId,</code><code> long tenantId,</code><code> long instanceId,</code><code> String businessType,</code><code> String businessId,</code><code> String result,</code><code> Instant completedAt</code><code>) {}Each business module handles its own events:
@Component</code><code>public class PurchaseWorkflowHandler {</code><code> private final PurchaseService purchaseService;</code><code> public PurchaseWorkflowHandler(PurchaseService purchaseService) {</code><code> this.purchaseService = purchaseService;</code><code> }</code><code> public void handle(WorkflowCompletedEvent event) {</code><code> if (!"PURCHASE".equals(event.businessType())) return;</code><code> purchaseService.applyWorkflowResult(</code><code> event.tenantId(),</code><code> event.businessId(),</code><code> event.instanceId(),</code><code> event.result()</code><code> );</code><code> }</code><code>}Messages may be redelivered; business modules must implement idempotency using process instance ID and event ID. Also verify the business record's bound process instance to prevent a delayed old completion event from overwriting a new round's result. The engine owns process execution; business systems own business outcomes; they connect via a stable event protocol.
10. What a Lightweight Approval Engine Should Achieve
For most internal enterprise systems, v1 need not implement full BPMN or all complex workflow patterns. Spring Boot, MySQL, MyBatis, plus a visual process config page, cover many common needs. Overall architecture:
Process definition & version management
Instance & node execution tracking
Assignee resolution via strategy pattern
Condition evaluation with restricted expressions
Concurrency control via DB row locks on process instance
Outbox pattern for async notifications
Event‑driven integration with business systems
Multi‑tenant isolation: definitions, versions, org structure, assignee resolution, and task access all scoped to tenant
Tenants must not resolve approvers from other tenants, nor read/operate tasks of other tenants even if they know the task ID.
Before production, prioritize verifying these scenarios:
Three approvers approve simultaneously; next node created exactly once.
Approver and applicant act concurrently (approve vs withdraw); only one valid outcome.
ANY node passes; remaining tasks become invalid.
New process version published; running old instances unaffected.
After return‑for‑revision and resubmit, old tasks cannot be operated.
Duplicate notifications or service restarts do not cause duplicate node execution.
Cross‑tenant query, assignment, or operation is impossible.
These tests matter more than simple happy‑path API checks.
If the project later needs complex parallel gateways, fork/join, subprocesses, boundary events, cross‑system long transactions, or full BPMN modeling, adopting a mature engine like Flowable is usually more appropriate than building all execution semantics from scratch. The value of a lightweight custom engine lies in a well‑scoped business domain, controllable data model, and deep integration with the existing Java stack — not in replacing all mature workflow products.
Conclusion
A dynamic approval system appears to be a backend configuration feature but actually combines Java strategy pattern, state machine, rule evaluation, DB transactions, concurrency control, event‑driven architecture, and multi‑tenant data isolation. Once this engine is solid, adding leave, purchase, contract, expense, onboarding, permission requests, etc., no longer requires rewriting approval logic each time. Business developers only define their variables, call the process start API, and handle the final result. The engine handles all intermediate assignees, condition branches, and voting thresholds. This is a core abstraction worth investing in for Java enterprise applications. As the article states: "A truly mature approval system is not one where developers can quickly write ten approval flows, but one where the eleventh flow requires no developer changes to the approval code."
For questions about attribution, corrections or content rights, please contactand we will review it promptly.