Advanced · 12-minute read · Updated 24 November 2026

Invariants Must Protect State, Not Individual Functions

Инварианты должны защищать состояние, а не отдельную функцию
Temporary fallback cover; replace in editorial pass.

If a rule matters after a write, enforce it against the state that the write would produce—not only inside the function that first creates it. This article builds a reusable pre-write check that prevents duplicate published articles through both POST and PUT paths.

The real failure mode

An invariant is a condition that must remain true for every valid version of a system’s data. Consider this rule:

A publication may have at most one published article for a given canonical slug.

A common implementation puts the check in the creation handler:

POST /articles
  if another published article has slug "release-notes":
      reject
  insert article

That appears correct until an update path can change a draft into a published article or change its slug:

PUT /articles/42
  update title, slug, and status
  save article

The creation handler protects one function. The invariant concerns the resulting database state. If POST checks the rule but PUT does not, the same invalid state remains reachable.

The durable design is to make every write path compute the proposed final state, then pass that state through the same guard before persistence.

Define the invariant precisely

Vague rules produce incomplete checks. Write the rule as a predicate over stored state:

For every publication P and normalized slug S:
count(article where article.publication_id = P
                   and article.slug = S
                   and article.status = "published") <= 1

This definition makes three details explicit:

  • The scope is one publication.
  • The comparison uses a normalized slug.
  • Only articles with published status participate.

A draft with the same slug is allowed. A published article with a different slug is allowed. A second published article with the same normalized slug is not.

Compute the final state before writing

The guard should receive a complete candidate object, not a partial request body. That distinction matters for updates: a PUT request may change only the status, while the slug and publication identifier come from the existing record.

function normalizeSlug(value) {
  return value
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
}

function buildCandidate(existing, input) {
  return {
    id: existing?.id ?? null,
    publicationId: input.publicationId ?? existing?.publicationId,
    slug: normalizeSlug(input.slug ?? existing?.slug ?? ""),
    status: input.status ?? existing?.status ?? "draft",
    title: input.title ?? existing?.title ?? ""
  };
}

The order is important:

  1. Load the current record for an update.
  2. Merge stored values with requested changes.
  3. Normalize values used by the invariant.
  4. Run the pre-write guard against the candidate.
  5. Persist only after the guard accepts it.

Checking the raw input is insufficient. If an existing article has slug release-notes and the request changes only status to published, the guard still needs to evaluate the existing slug.

Put the rule at the state boundary

The reusable guard can be expressed as a pure decision around a repository query:

async function assertPublishableArticle(candidate, articles) {
  if (candidate.status !== "published") {
    return;
  }

  const conflict = await articles.findPublishedByPublicationAndSlug({
    publicationId: candidate.publicationId,
    slug: candidate.slug,
    excludeId: candidate.id
  });

  if (conflict) {
    throw new ConflictError(
      "A published article already uses this slug in this publication"
    );
  }
}

The excludeId parameter is required for updates. Otherwise, an article would conflict with itself whenever it is saved without changing its slug.

The guard is intentionally independent of POST and PUT. It describes what must be true before a candidate enters persistent state. Both handlers can therefore use the same pre-write operation.

Apply the same guard to POST and PUT

Creation path

async function createArticle(request) {
  const candidate = buildCandidate(null, request.body);

  await assertPublishableArticle(candidate, articleRepository);

  return articleRepository.insert(candidate);
}

Update path

async function updateArticle(request) {
  const existing = await articleRepository.findById(request.params.id);

  if (!existing) {
    throw new NotFoundError("Article not found");
  }

  const candidate = buildCandidate(existing, request.body);

  await assertPublishableArticle(candidate, articleRepository);

  return articleRepository.update(candidate.id, candidate);
}

The important property is not that the handlers look identical. It is that both produce the same kind of candidate and both invoke the same guard before writing.

If the application has more write paths—an import job, an administration command, a moderation workflow, or a background synchronization process—each path should converge on the same state boundary rather than duplicate the rule.

Prefer a database constraint for the final guarantee

An application-level check improves behavior and error messages, but two concurrent requests can both observe no conflict before either one commits. This is a race condition.

Where the database supports it, add a unique constraint that matches the invariant. For a system with publication, normalized slug, and status columns, a partial unique index is one possible configuration:

CREATE UNIQUE INDEX one_published_article_per_slug
ON articles (publication_id, slug)
WHERE status = 'published';

The exact syntax depends on the database engine. If partial indexes are unavailable, an equivalent design may use a generated key or a separate table containing only published-slug claims.

The application guard and the database constraint have different jobs:

  • The pre-write guard gives callers a predictable domain error before attempting the write.
  • The database constraint protects the invariant under concurrency and against missed code paths.
  • The write boundary translates a constraint violation into the same conflict response used by the guard.

Treat the database constraint as the final safety net, not as a reason to leave one handler unchecked. A guard still makes validation explicit and keeps the failure close to the request.

Reproducible verification

The following examples describe checks to run in a project with an HTTP API and a test database. They are commands and expected assertions, not claims that this article has executed them.

1. Create a published article

curl -i -X POST http://localhost:3000/publications/demo/articles \
  -H 'Content-Type: application/json' \
  -d '{
    "title": "Release notes",
    "slug": "release-notes",
    "status": "published"
  }'

Record the returned article identifier. The response should indicate a successful creation.

2. Try to create the duplicate through POST

curl -i -X POST http://localhost:3000/publications/demo/articles \
  -H 'Content-Type: application/json' \
  -d '{
    "title": "Another release notes page",
    "slug": "release-notes",
    "status": "published"
  }'

Verify that the request is rejected with the project’s conflict response and that the database still contains only one published article for the normalized key.

3. Create a draft, then publish it through PUT

curl -i -X POST http://localhost:3000/publications/demo/articles \
  -H 'Content-Type: application/json' \
  -d '{
    "title": "Draft release notes",
    "slug": "release-notes",
    "status": "draft"
  }'

Then update the returned draft identifier:

curl -i -X PUT http://localhost:3000/publications/demo/articles/DRAFT_ID \
  -H 'Content-Type: application/json' \
  -d '{
    "status": "published"
  }'

The update should be rejected because the candidate’s final state has the same publication, normalized slug, and published status as the existing article. Crucially, the request body does not include the slug; the guard must evaluate the merged candidate.

4. Verify the allowed cases

  • Two drafts may share a slug if the product permits it.
  • Published articles in different publications may share a slug.
  • A published article may update its title without conflicting with itself.
  • A published article may change to a new, unused slug.
  • A published article may be archived or returned to draft if the state model allows it.

Failure cases to test deliberately

Partial updates that omit invariant fields

A status-only update must still carry the stored slug into the candidate. Testing only full request bodies misses this path.

Normalization mismatches

Decide whether Release-Notes, release notes, and release-notes are equivalent. Apply the same normalization when writing, querying, indexing, and checking conflicts.

Self-conflict on update

Exclude the current record by identifier. A guard that queries for any matching row will reject harmless saves.

Concurrent writes

Run two publication requests at the same time against an empty key. The expected durable result is one success and one conflict, supported by a database constraint or an equivalent serialized write mechanism.

Soft-deleted records

If deleted rows remain in the database, define whether they participate in the invariant. The query and constraint must use the same rule.

Import and administrative paths

Search for every operation that can set status = 'published' or change the slug. A correct API handler does not protect a batch import that writes directly to the repository.

Transactions and error handling

If the guard reads related records and the write changes several tables, place the read and write in one transaction where the database design requires it. A transaction alone does not automatically prevent every concurrent conflict; the isolation level and constraint still matter.

Handle both application-detected conflicts and database constraint violations:

try {
  return await database.transaction(async (tx) => {
    const candidate = await buildCandidateInTransaction(tx, request);
    await assertPublishableArticle(candidate, tx.articles);
    return tx.articles.save(candidate);
  });
} catch (error) {
  if (isPublishedSlugConstraintViolation(error)) {
    throw new ConflictError(
      "A published article already uses this slug in this publication"
    );
  }

  throw error;
}

Do not expose raw database error text to clients. Keep the public error stable while logging enough structured context for diagnosis without including secrets or unnecessary personal data.

What this pattern does not solve

A state-level guard is not a substitute for a complete publication model. It does not decide which article should win, how redirects should work after a slug change, whether two languages may reuse a slug, or how scheduled publication interacts with time zones.

It also does not prove that all writes use the guard. You still need repository-level searches, integration tests for each write path, and a database-level guarantee where concurrent access is possible.

Finally, the phrase “one published article” must have a precise scope. The key may need to include locale, site, tenant, content type, or an effective publication window. Add those dimensions to both the candidate and the constraint when the product rule requires them.

The reusable rule

When a business rule describes valid stored state, make the rule reusable at the pre-write boundary:

current state
    + requested change
    ------------------
    = candidate final state

candidate final state
    - shared invariant guard
    - database constraint
    --------------------
    = accepted or rejected write

This changes the question from “Did this function remember to validate?” to “Can any write enter a state that violates the rule?” That is the right level for invariants.

For more implementation patterns, see the guides and the glossary.

We publish what works for us—and implement the same solutions for your business. We design AI automation, Telegram bots, chats, and AI agents for real-world processes. Discuss your project →