Skip to content

Concurrency Pipeline

Use the Concurrency Pipeline to automatically retry a Command when its execution returns a concurrency conflict.

The pipeline is useful with optimistic concurrency, where two operations can attempt to update the same resource and one operation may fail because the resource version has changed.

The concurrency retry configuration belongs to the command bus. It does not apply to queries.

You need:

  • an XenoAppBuilder instance;
  • a Command and its handler;
  • concurrency conflicts represented as a failed Result with a conflict error;
  • the command executed through the Xeno.JS mediator.

If you are creating the Command itself, see Create a Command.

Pass withConcurrency() to addPipeline() and configure its options in the callback:

import { XenoAppBuilder, withConcurrency } from '@xeno-js/core'
const app = new XenoAppBuilder()
.addPipeline(withConcurrency((options) => {
options.maxRetries = 3
options.delayConfig = {
baseDelayMs: 100,
maxJitterMs: 50,
}
}))
.build()

Once configured, Xeno.JS adds the concurrency retry behavior to the Command pipeline.

You do not need to register ConcurrencyRetryPipeline manually.

Use maxRetries to control the maximum number of command pipeline attempts, including the first execution.

For example:

withConcurrency((options) => {
options.maxRetries = 3
options.delayConfig = {
baseDelayMs: 100,
maxJitterMs: 50,
}
})

With maxRetries: 3, a command can be executed up to three times when it keeps returning a concurrency conflict:

Attempt 1
│
├── success ───────────────► return result
│
└── conflict
│
▼
delay
│
▼
Attempt 2
│
├── success ───────────────► return result
│
└── conflict
│
▼
delay
│
▼
Attempt 3
│
├── success ───────────────► return result
│
└── conflict ───────────────► return failed Result

Use a positive integer for maxRetries. The retry pipeline does not validate this value.

Use delayConfig to configure the delay applied between concurrency-conflict attempts. The pipeline waits for baseDelayMs plus a random jitter from zero up to (but not including) maxJitterMs; it does not increase the base delay on later attempts.

withConcurrency((options) => {
options.maxRetries = 5
options.delayConfig = {
baseDelayMs: 100,
maxJitterMs: 50,
}
})

baseDelayMs defines the fixed base delay in milliseconds before another attempt. Use a non-negative integer; the retry pipeline does not validate this value.

baseDelayMs: 100

maxJitterMs defines the upper bound, in milliseconds, for the random jitter added to the base delay. Use a non-negative integer; the retry pipeline does not validate this value.

maxJitterMs: 50

Using jitter helps avoid multiple concurrent operations retrying at exactly the same time.

The concurrency configuration is optional.

You can enable it with the defaults:

const app = new XenoAppBuilder()
.addPipeline(withConcurrency())
.build()

When a value is omitted, the pipeline defaults are used: maxRetries is 3, baseDelayMs is 20, and maxJitterMs is 30.

You can override only the retry count:

const app = new XenoAppBuilder()
.addPipeline(withConcurrency((options) => {
options.maxRetries = 5
}))
.build()

Or provide the complete configuration:

const app = new XenoAppBuilder()
.addPipeline(withConcurrency((options) => {
options.maxRetries = 5
options.delayConfig = {
baseDelayMs: 100,
maxJitterMs: 50,
}
}))
.build()

Use intentRegistry to override retry settings for specific command intents. The registry key must match the command’s intent. Settings defined for an intent take precedence over the corresponding global options; any omitted fields fall back to the global configuration and then to the pipeline defaults.

For example, set global options and give selected commands their own retry limits and delays:

const app = new XenoAppBuilder()
.addPipeline(withConcurrency((options) => {
options.maxRetries = 3
options.delayConfig = {
baseDelayMs: 100,
maxJitterMs: 50,
}
options.intentRegistry = {
UpdateUserCommand: {
maxRetries: 5,
},
SubmitPaymentCommand: {
maxRetries: 2,
delayConfig: {
baseDelayMs: 250,
maxJitterMs: 100,
},
},
}
}))
.build()

In this example, UpdateUserCommand uses five attempts with the global delay settings. SubmitPaymentCommand uses two attempts and its own delay settings. Commands not listed in intentRegistry use the global options.

The retry pipeline does not retry every failed command.

A result is retried only when its error is a conflict with:

  • the CONFLICT error code;
  • HTTP status 409.

For example, a command handler can return a conflict result when an optimistic concurrency check detects that the entity was modified by another operation.

return Result.fail(
AppError.conflict(
request.intent,
'The user was modified by another request.',
),
)

That failed result is eligible for the concurrency retry pipeline.

Other failures are returned immediately.

For example:

Command
│
▼
Handler
│
├── success ───────────────► return result
│
├── validation error ──────► return error
│
├── authorization error ───► return error
│
└── conflict (409) ────────► retry

When a command returns a concurrency conflict:

  1. Xeno.JS checks whether the error is a conflict;
  2. if the retry limit has not been reached, it waits using the configured delay and jitter;
  3. the command pipeline is executed again;
  4. the new result is evaluated again.

A successful retry immediately returns the successful result.

For example:

Command
│
▼
Conflict
│
▼
wait
│
▼
Command again
│
▼
Success
│
▼
Return success

A non-concurrency error is not retried.

If every allowed attempt returns a concurrency conflict, the pipeline stops retrying and returns a failed conflict Result.

The returned error indicates that the maximum retry attempts were exceeded.

For example:

Maximum retry attempts (3) exceeded due to concurrency conflicts.

The command is not executed again after the limit has been reached.

A typical application can configure the command bus as follows:

import { XenoAppBuilder, withConcurrency } from '@xeno-js/core'
const app = new XenoAppBuilder()
.addPipeline(withConcurrency((options) => {
options.maxRetries = 3
options.delayConfig = {
baseDelayMs: 100,
maxJitterMs: 50,
}
}))
.build()

Your command handler is responsible for returning a conflict when an optimistic concurrency check fails:

import { AppError, Result } from '@xeno-js/shared'
export class UpdateUserHandler extends BaseHandler<
UpdateUserCommand,
UpdateUserResult
> {
protected async executeAsync(
request: UpdateUserCommand,
): Promise<Result<UpdateUserResult>> {
const user = await this.userRepository.findById(request.userId)
if (!user) {
return Result.fail(
AppError.notFound(
request.intent,
'User not found.',
),
)
}
if (user.version !== request.version) {
return Result.fail(
AppError.conflict(
request.intent,
'The user was modified by another request.',
),
)
}
// Update the entity and persist it.
return Result.ok({
userId: user.id,
})
}
}

With concurrency retries enabled, a conflict can cause the command to be executed again according to the configured retry policy.

The retry options are provided to:

withConcurrency((options) => {
options.maxRetries = 3
})

The plugin adds the retry behavior to the Command pipeline; it does not add retry behavior to the Query pipeline.

The application pipeline is conceptually:

Command
│
▼
Common pipelines
│
▼
Command-specific pipelines
│
└── Concurrency Retry
│
▼
Handler

If you need query result caching or other query-specific behavior, see the corresponding query pipeline documentation.

The retry pipeline retries only failed results whose error code is CONFLICT and whose HTTP status is 409. Other errors are returned without retrying.

For example:

Non-conflict error
│
└──► return immediately
Conflict / 409
│
└──► retry

Increasing maxRetries does not cause errors that fail either conflict check to be retried.

Check that withConcurrency() is passed to addPipeline():

import { withConcurrency } from '@xeno-js/core'
app.addPipeline(withConcurrency((options) => {
options.maxRetries = 3
}))

Then check that the handler returns a conflict error.

The retry pipeline only recognizes errors with:

  • conflict error code;
  • HTTP status 409.

A generic failed Result will not trigger a retry.

Check the error returned by the handler.

For example, this is a concurrency conflict:

return Result.fail(
AppError.conflict(
request.intent,
'Concurrent update detected.',
),
)

Whereas returning another error type will not activate the retry behavior.

Use a positive integer for maxRetries. The retry pipeline does not validate this value.

Not recommended:

maxRetries: 0

Not recommended:

maxRetries: -1

Recommended:

maxRetries: 3

baseDelayMs or maxJitterMs has an unexpected value

Section titled “baseDelayMs or maxJitterMs has an unexpected value”

Use non-negative integers for baseDelayMs and maxJitterMs. The retry pipeline does not validate these values.

Not recommended:

delayConfig: {
baseDelayMs: -100,
maxJitterMs: 50,
}

Recommended:

delayConfig: {
baseDelayMs: 100,
maxJitterMs: 50,
}

Xeno.JS is an MIT-licensed open source project. It can grow thanks to the support of these awesome people. If you’d like to join them, please read more at support section