Skip to content

Serialization conflicts

Why a request's unit observes a serialization conflict and never retries it, and retry_on_conflict, the service's primitive that does.

A serialization failure or a deadlock aborts the transaction it struck. The request’s unit of work reports it; a service retries it, at a boundary it knows is replayable.

Why retrying belongs to the service, not the request

Section titled “Why retrying belongs to the service, not the request”

A request’s body is consumed by the handler that reads it — the bytes are gone past the handler call. The edge cannot replay the same handler on a fresh transaction; the DatabaseTransaction handle is already aborted by the time a conflict surfaces. Two consequences:

  1. The request’s unit observes the conflict, it does not retry it. The failed commit has already consumed its handle, and the handler’s non-transactional side effects — an object written to storage, a call to another service — would replay with it. (An emitted event and a pushed job are not among them: both wait for the commit, and a failed one drops them.)
  2. Retrying is the service’s job. Only the service knows which boundary is replayable, so the replayable closure owns that boundary itself.

The framework exposes two pieces, deliberately split:

Terminal window
NESTRS_SEAORM__OBSERVE_SERIALIZATION_CONFLICTS=true
apps/api/src/module.rs
SeaOrmModule::for_root(SeaOrmConfig {
observe_serialization_conflicts: true,
..Default::default()
})

With the flag on, the unit of work matches a request’s commit-time conflict against the SQLSTATE markers below and logs it at warn with the conflict tag (target nest_rs::orm) so ops sees the failure mode distinctly from a generic commit error.

For an actually-retried operation, wrap a replayable closure in retry_on_conflict inside a service method that owns its programmatic transaction boundary:

crates/features/src/posts/service.rs
use std::sync::Arc;
use std::time::Duration;
use nest_rs::seaorm::retry::{
retry_on_conflict, DEFAULT_RETRY_ATTEMPTS, DEFAULT_INITIAL_BACKOFF,
};
use sea_orm::{DatabaseConnection, TransactionTrait};
use nest_rs::seaorm::ServiceError;
use uuid::Uuid;
impl PostsService {
pub async fn publish(&self, id: Uuid) -> Result<post::Model, ServiceError> {
let db = self.db.clone();
retry_on_conflict(DEFAULT_RETRY_ATTEMPTS, DEFAULT_INITIAL_BACKOFF, || {
let db = db.clone();
async move {
let txn = db.begin().await?;
let published = read_update_insert(&txn, id).await?;
txn.commit().await?;
Ok::<_, sea_orm::DbErr>(published)
}
})
.await
.map_err(ServiceError::from)
}
}

The closure’s transaction is yours, committed out of the framework’s sight, so an event emitted inside it would not wait for it: emit once retry_on_conflict has returned Ok, after the commit that stood.

retry_on_conflict runs the closure up to attempts times, sleeping initial_backoff << attempt between tries (5 ms → 10 ms → 20 ms with the defaults), each sleep scaled by a jitter between 0.8 and 1.2 drawn per call — two transactions that conflicted with each other retry apart, not at one instant into the same conflict. A non-retryable error returns immediately; a retryable one is logged at warn and the closure re-runs from scratch — that’s what makes the retry honest, the body re-opens a fresh transaction against a fresh snapshot.

The defaults are conservative on purpose:

ConstantValue
DEFAULT_RETRY_ATTEMPTS3
DEFAULT_INITIAL_BACKOFF5 ms
MAX_RETRY_ATTEMPTS32 (hard ceiling)
Per-sleep cap30 s, before jitter

The two limits bound what a caller can ask for: no sleep goes past 30 s before jitter, however many attempts have failed, and no call makes more than 32 attempts, so a call passing usize::MAX still ends in bounded time.

SQLSTATEBackend(s)What it means
40001Postgres, MySQLSerialization failure
40P01PostgresDeadlock detected
1213MySQLDeadlock found
1205SQL ServerTransaction was deadlock victim

Anything else — 23505 (unique violation), RecordNotFound, a generic Internal error whose message contains “40001” — returns immediately. A unique-violation retry would loop forever; a substring match on the message would falsely retry a connection log mentioning port 40001. The classifier reads the typed code only, never the display string.

The failure modes a retry cannot fix:

  • A unique constraint violation. Retrying inserts the same row again, same failure. The classifier rejects these.
  • A row that doesn’t exist. RecordNotFound is terminal — no amount of retries materialize the row.
  • Application-side validation. The closure answers a DbErr, so a ServiceError::Validation never reaches the classifier: validate before the retry, since the same input fails the same way.
  • A handler-time conflict on the auto-commit transaction. The request’s unit cannot retry the body; the conflict surfaces as a RepoError::SerializationFailure from the service, which gets mapped to the appropriate HTTP status. Use retry_on_conflict at the service level instead.

The split is deliberate. The request’s unit handles the common case transparently (open / commit / rollback); the service handles the hard case explicitly (replay the work against a fresh snapshot). One way to do each.