Skip to content

How-to: soft delete (logical deletion)

A pattern for logical deletion using a deleted_at: datetime | None field.


Domain entity

python
from dataclasses import dataclass
from datetime import UTC, datetime

@dataclass(frozen=True, slots=True)
class Article:
    article_id: int
    title: str
    deleted_at: datetime | None = None

    @property
    def is_deleted(self) -> bool:
        return self.deleted_at is not None

The is_deleted property keeps the business logic inside the domain, so callers don't have to reason about deleted_at is not None.


Updating a frozen dataclass: dataclasses.replace()

python
from dataclasses import replace

article = replace(article, deleted_at=datetime.now(UTC))

A frozen=True dataclass can't have its fields mutated directly, but replace() creates a new instance.


DELETE endpoint (idempotent)

python
@app.delete("/articles/{article_id}", status_code=204)
def delete_article(article_id: int) -> None:
    article = _store.get(article_id)
    if article is None or article.is_deleted:
        return  # idempotent: already-deleted or missing also returns 204
    _store[article_id] = replace(article, deleted_at=datetime.now(UTC))

Per RFC 9110, DELETE is idempotent. A DELETE against a missing or already-deleted resource also returns 204.


Excluding in list / get

python
def _active_articles() -> list[Article]:
    return [a for a in _store.values() if not a.is_deleted]

@app.get("/articles", response_model=list[ArticleResponse])
def list_articles() -> list[ArticleResponse]:
    return [ArticleResponse.from_domain(a) for a in _active_articles()]

@app.get("/articles/{article_id}", response_model=ArticleResponse)
def get_article(article_id: int) -> ArticleResponse | JSONResponse:
    article = _store.get(article_id)
    if article is None or article.is_deleted:
        return problem_details_response("not-found", "Not Found", 404, "Article not found.")
    return ArticleResponse.from_domain(article)  # return the model on success (default pattern)

Excluding deleted_at from the response

Simply don't define a deleted_at field on ArticleResponse. Pydantic does not serialize fields that aren't defined.

python
class ArticleResponse(BaseModel):
    article_id: int
    title: str
    # deleted_at not included → the logical-delete implementation detail doesn't leak to the public API

Returning deleted_at only on admin endpoints is the recommended design.


See also

  • FT110: docs/field-trials/2026-05-field-trial-110.md

Released under the MIT License.