# Mutex Lock

> Ensures exclusive access to a critical section of the workflow via a distributed lock.

Source: https://docs.sommatic.ai/en/nodes/flow.mutex/

- Slug: `flow.mutex`
- Family: Flow control
- Version: 1.0.0
- Status: Experimental. Computes the lock key and returns it in `meta.mutex`, but the execution engine never reads it: no lock is acquired and execution always continues through `out`.
- Execution: sync

Ensures exclusive access to a critical section of the workflow via a distributed lock.

When multiple workflow instances (or parallel branches) try to access a shared resource simultaneously, a Mutex (Mutual Exclusion) ensures only one can proceed at a time. Other instances will wait until the lock is released or a timeout occurs.

**Behavior:**
- **Acquire:** Attempts to lock the key. If free, lock is granted.
- **Wait:** If locked, the process spins/waits.
- **Release:** The lock is automatically released after the TTL expires (to prevent deadlocks).

**Use Cases:**
- Preventing double-spending on a user wallet.
- Serializing access to a legacy system that cannot handle concurrency.
- Ensuring "Check-then-Act" atomicity in database operations.

## Configuration

- `key_expr` (string, required, accepts expressions): JSONata expression to derive the unique lock ID (e.g. `data.userId`).
- `ttl_seconds` (integer, optional): Safety timeout to automatically release the lock if the workflow crashes. Default: `30`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `out` (default): Lock successfully acquired. Proceed with critical section.
- `timeout`: Failed to acquire lock within the system limit.
- `error`: System error during locking.

## Input contract

- `payload` (object, optional)

## Output contract

- `payload` (object, optional)

## In expressions

What a later node can read from this node's output with `$("Mutex Lock").item.json.<path>` (write your node's label instead of `Mutex Lock`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `out`, from the output shown in Ports.

- `$("Mutex Lock").item.json.payload` (object) **The worker does not return it: reads as undefined.**
- `$("Mutex Lock").item.json.user_id` (string) = `"u-42"` (Not suggested by the editor)
- `$("Mutex Lock").item.json.action` (string) = `"export"` (Not suggested by the editor)


## How it works

Experimental. Computes a lock key and passes the payload through `out`; no lock is acquired, because the engine never reads the lock request.

1. Resolves the config; `ttl_seconds` defaults to 30.
2. If the original `key_expr` text contains `{{`, the resolved value is used as the key (converted to a string). Otherwise `key_expr` is evaluated as JSONata against the payload (`user_id`); a falsy result or no `key_expr` gives `global_lock`.
3. Returns the payload unchanged through `out` with `meta.mutex` `{ action: "acquire", key, ttl }`.
4. The engine ignores `meta.mutex`: nothing is locked, nothing waits and concurrent runs are not serialized.

## In a workflow

### Node

```json
{
  "node_id": "node-lock-user",
  "label": "Lock user",
  "operator_slug": "flow.mutex",
  "operator_version": "1.0.0",
  "config": {
    "key_expr": "{{ $json.user_id }}",
    "ttl_seconds": 30
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "user_id": "u-42",
    "action": "export"
  },
  "port": "out",
  "meta": {
    "mutex": {
      "action": "acquire",
      "key": "u-42",
      "ttl": 30
    }
  }
}
```

## Output ports (behaviour in the code)

### `out`

Always, including when the JSONata key fails (see errors).

```json
{
  "user_id": "u-42",
  "action": "export"
}
```

### `timeout`

Never emitted.

### `error`

Never emitted.

## Behaviour in the code

- `ttl_seconds`: Only echoed in `meta.mutex.ttl`.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Lock key evaluation failed` | `out` | `key_expr` is invalid JSONata. The envelope has no port, so the engine routes it to `out` and the next node receives `{ ok: false, errors: ["Lock key evaluation failed"] }` as its payload. |

## Notes and limits

- Not implemented: the engine has no lock store. Do not rely on this node for mutual exclusion; make the protected operation idempotent instead.
- `meta` is recorded in the run steps only: downstream nodes receive `data` as their payload and cannot read `meta` through `$json` or `$("Node")`.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "flow.mutex",
  "name": "Mutex Lock",
  "category": "flow",
  "version": "1.0.0",
  "description": "Ensures exclusive access to a critical section of the workflow via a distributed lock.\n\n  When multiple workflow instances (or parallel branches) try to access a shared resource simultaneously, a Mutex (Mutual Exclusion) ensures only one can proceed at a time. Other instances will wait until the lock is released or a timeout occurs.\n\n  **Behavior:**\n  - **Acquire:** Attempts to lock the key. If free, lock is granted.\n  - **Wait:** If locked, the process spins/waits.\n  - **Release:** The lock is automatically released after the TTL expires (to prevent deadlocks).\n\n  **Use Cases:**\n  - Preventing double-spending on a user wallet.\n  - Serializing access to a legacy system that cannot handle concurrency.\n  - Ensuring \"Check-then-Act\" atomicity in database operations.",
  "capabilities": [
    "locking",
    "concurrency",
    "safety"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "key_expr": {
        "type": "string",
        "title": "Lock Key",
        "format": "expression",
        "description": "JSONata expression to derive the unique lock ID (e.g. `data.userId`)."
      },
      "ttl_seconds": {
        "type": "integer",
        "default": 30,
        "title": "Lock TTL (Seconds)",
        "description": "Safety timeout to automatically release the lock if the workflow crashes."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "key_expr"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Payload to evaluate the key against.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Passes through the original payload.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Acquired",
      "is_default": true,
      "description": "Lock successfully acquired. Proceed with critical section."
    },
    {
      "port_id": "timeout",
      "label": "Timeout",
      "description": "Failed to acquire lock within the system limit."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "System error during locking."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "lock",
    "mutex",
    "atomic",
    "concurrency"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "key_expr": {
      "type": "string",
      "title": "Lock Key",
      "format": "expression",
      "description": "JSONata expression to derive the unique lock ID (e.g. `data.userId`)."
    },
    "ttl_seconds": {
      "type": "integer",
      "default": 30,
      "title": "Lock TTL (Seconds)",
      "description": "Safety timeout to automatically release the lock if the workflow crashes."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "key_expr"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Payload to evaluate the key against.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Passes through the original payload.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Acquired",
    "is_default": true,
    "description": "Lock successfully acquired. Proceed with critical section."
  },
  {
    "port_id": "timeout",
    "label": "Timeout",
    "description": "Failed to acquire lock within the system limit."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "System error during locking."
  }
]
```
