Related data and reindexing

Copy Markdown View Source

This guide is for the Phoenix or Ecto team that has moved beyond flat documents and now needs to answer the uncomfortable real-app question:

What should happen when a record changes data that lives in someone else's search document?

Examples:

  • an Author name changes and post documents store author_name
  • a Tag is renamed and product documents store tag labels
  • an account changes status and many searchable child records should now filter differently
  • a support ticket changes teams and search documents store team metadata

The short version is simple:

Scrypath does not hide cross-record invalidation behind callback magic. Your app owns the fan-out.

That is the least-surprise Ecto shape, and it keeps recovery honest when the blast radius is larger than one row.

The rule of thumb

Use simple Scrypath.sync_record/3 when the changed row is the same row that owns the search document.

Reach for explicit fan-out when:

  • the indexed document includes data from associated records
  • a shared lookup table changes many documents at once
  • a permission or tenant boundary change affects search visibility
  • the shape of the document changed and you no longer trust the live index

If you remember one sentence from this guide, make it this:

Find affected source records explicitly, then sync or rebuild them deliberately.

1. One changed row, one changed document

This is the easy case.

Example:

  • a Post title changes
  • a Customer email changes
  • a Ticket status changes and the document is built from the ticket row itself

Do this:

You do not need a broader recovery workflow unless the sync fails or the contract changed.

2. One changed row affects many other documents

This is the common real-app footgun.

Example:

  • an Author rename should update every searchable post that stores author_name
  • a Category label change should update every product document that stores category names
  • an organization rename should update many user-facing result documents

Do this:

  • persist the changed row in its owning context
  • query for the affected source records explicitly
  • sync those source records in a deliberate follow-up step

In Ecto terms, this usually means:

  • identify the source schema that owns the search document
  • build one query that finds affected records
  • decide whether the follow-up should be inline, queued, or manual

The important thing is what you do not promise:

  • no hidden association walking
  • no automatic preload magic
  • no assumption that a related-row change is cheap

When one changed row fans out to many search documents, Scrypath ships an explicit entrypoint for it: Scrypath.sync_related/3. The context invokes it deliberately; it is not a hidden callback. You declare the fan-out as metadata on the owning schema, write one resolver that finds the affected target records, and the context calls sync_related/3 choosing inline or durable (Oban) execution.

There is no public worker macro to write. The :oban path is dispatched by an internal Scrypath worker; adopters never name or use a worker module. You select durable execution with sync_mode: :oban and point Scrypath at your Oban instance.

(a) Declare the fan-out on the owning schema

The fan-out lives on the schema whose change drives the update — here Author, because an author rename should re-sync every post that stores author_name. fan_outs: names a key (:posts), a target: schema (the schema that owns the search document), and a resolver: MFA tuple that maps the changed owner(s) to the target records to re-sync:

defmodule MyApp.Accounts.Author do
  use Ecto.Schema

  schema "authors" do
    field(:name, :string)
    has_many(:posts, MyApp.Blog.Post)
    timestamps()
  end

  use Scrypath,
    fields: [:name],
    fan_outs: [
      posts: [
        target: MyApp.Blog.Post,
        resolver: {MyApp.Accounts, :resolve_posts_for_authors, []}
      ]
    ]

  # Used by the :oban fan-out enqueue path (Scrypath.Identity.document_ids/2).
  def __scrypath__(:document_id), do: :id

  def changeset(author, attrs) do
    author
    |> Ecto.Changeset.cast(attrs, [:name])
    |> Ecto.Changeset.validate_required([:name])
  end
end

For ordinary schemas, declare fan-out with use Scrypath, fan_outs:. Scrypath generates __scrypath__(:fan_outs) for this path, and Scrypath.sync_related/3 consumes that generated __scrypath__(:fan_outs) metadata at runtime.

Hand-written __scrypath__/1 remains supported as a low-level escape hatch for owner-only schemas that intentionally do not use Scrypath; it is not the normal copy-paste path for searchable schemas.

The document_id reflection key is already generated by use Scrypath. Define it by hand only if the owning schema does not use use Scrypath but still participates in fan-out.

The resolver MFA is invoked as apply(mod, fun, [first_arg | extra_args]). The [] above means no extra args; first_arg is the list of owning-schema records, the same in every sync mode (see (c)).

(b) Call sync_related/3 from the context — inline or oban

The owning context persists the change, keeps any denormalized projection in sync, and then invokes the fan-out explicitly. opts[:fan_out] is required — it names a key in the schema's fan_outs: declaration, and sync_related/3 raises ArgumentError if it is absent.

Inline execution resolves and syncs the affected records now, in the calling process:

# inline (context-side) — resolves + syncs in this process, returns when done
{:ok, %{mode: :inline, status: :completed}} =
  Scrypath.sync_related(Author, updated_author,
    fan_out: :posts, sync_mode: :inline, backend: Scrypath.Meilisearch)

Oban execution enqueues the internal RelatedWorker and returns immediately — the work is durably queued, not done:

# oban (context-side) — "durably queued", NOT "searchable now"
{:ok, %{mode: :oban, status: :accepted}} =
  Scrypath.sync_related(Author, updated_author,
    fan_out: :posts, sync_mode: :oban, oban: MyApp.Oban,
    oban_queue: :scrypath, backend: Scrypath.Meilisearch, repo: MyApp.Repo)

Note the status difference: :inline returns status: :completed (the documents are synced); :oban returns status: :accepted (the job is queued and will run later).

(c) What your resolver receives

A resolver always receives a non-empty list of current owning-schema records ([%Author{} | _]) and returns the target records to re-sync. This is the same under sync_mode: :inline and sync_mode: :oban:

  • The inline path passes the structs you gave sync_related/3, in the calling process.
  • The oban path cannot carry structs through a job, so each job carries the owners' document IDs. When the job runs, the internal worker reloads the current records with the schema's loader (preload: or search_records/2) and passes those records to your resolver.

One clause that takes records is enough:

defmodule MyApp.Accounts do
  import Ecto.Query
  alias MyApp.Accounts.Author
  alias MyApp.Blog.Post
  alias MyApp.Repo

  def update_author(%Author{} = author, attrs, sync_opts) do
    {:ok, updated} =
      author |> Author.changeset(attrs) |> Repo.update()

    # Keep the denormalized projection in sync — app-owned, explicit, before fan-out.
    {_count, _} =
      from(p in Post, where: p.author_id == ^updated.id)
      |> Repo.update_all(set: [author_name: updated.name])

    # Explicit fan-out the context invokes after the write commits — not a callback.
    {:ok, result} =
      Scrypath.sync_related(Author, updated, Keyword.put(sync_opts, :fan_out, :posts))

    {:ok, result, updated}
  end

  # Receives Author records in every sync mode.
  def resolve_posts_for_authors([%Author{} | _] = authors) do
    author_ids = Enum.map(authors, & &1.id)
    Repo.all(from(p in Post, where: p.author_id in ^author_ids))
  end
end

If your resolver still has a clause that takes ids (the old :oban shape), that clause is now dead code and safe to remove.

What to expect at the edges:

  • Triggers that no longer load are skipped under :oban. A deleted owner, or one that search_records/2 excludes (for example a soft-deleted row), is left out of the list your resolver receives. If none of a job's triggers load, the resolver is not called and the job succeeds. To hide the targets of a soft-deleted owner, sync them directly, for example Scrypath.sync_records(Post, posts).

  • Call sync_related/3 after the write commits, in every sync mode.

    • Under :oban, Scrypath collapses a sync into an identical pending job (conflict?: true) when you enqueue. Inside a transaction, the job you collapse into can start before your commit, load the old triggers and finish, and no job is left to fan out your change.
    • Under :oban, Oban also holds a lock on that unique job until your transaction ends. An identical sync_related/3 from another process during that time reports conflict?: true and inserts nothing, so if your transaction rolls back, neither fan-out runs.
    • Under :inline, the resolver and the backend write run immediately, so inside a transaction the backend would index rows that are not committed yet and may still roll back.

    The trade-off: a crash between the commit and the call misses that fan-out. Your data is committed, so re-running sync_related/3, a backfill of the target schema or a managed reindex brings the index back in line (see Drift recovery). If you do call it inside a transaction on the Oban repo, Scrypath won't break your transaction: see "Call sync functions after your write commits" in the sync modes guide.

  • Inline does not reload. Under :inline, a struct for a row you just deleted is still passed to the resolver, which usually returns [] because nothing references it any more. An empty trigger list is a noop in every mode: the resolver is not called.

  • No ordering contract. Triggers are deduped and sent in jobs of up to 1000 ids each. Do not rely on the order of the records your resolver receives.

  • The :oban path needs a way to load owners. Pass repo: (or configure it), or define search_records/2 on the owning schema; without either, sync_related/3 raises at the call site instead of failing inside the job. Tenant-scoped owners should define search_records/2 so the reload applies the tenant scope. A schema with a hand-written owner-only __scrypath__/1 keeps working.

Upgrading from 0.3.17 with :oban related jobs still queued. Scrypath 0.3.17 enqueued related jobs without a repo, and its worker passed the ids straight to the resolver. After the upgrade, the worker reloads the triggers first. A queued 0.3.17 job whose owning schema has no search_records/2, in an app that configures no :repo, cannot reload them: Oban cancels it with {:invalid_job, :repo_required} and that fan-out does not run. Before you deploy, do one of these:

  • configure a default repo (config :scrypath, :defaults, repo: MyApp.Repo), which queued jobs pick up when they run
  • define search_records/2 on the owning schema
  • let the related jobs (worker: "Scrypath.Sync.RelatedWorker") drain from the queue on the old version first

If some jobs were already cancelled, fix the configuration and retry them (for example from Oban Web), or run the fan-out again with Scrypath.sync_related/3.

3. The document contract changed

Sometimes the question is not "which records changed?"

Sometimes the question is:

Do I still trust the live index at all?

Examples:

  • you added or removed projected fields
  • you changed filterable, sortable, or faceting declarations
  • you changed settings in a way that implies a rebuild
  • you cannot confidently enumerate every affected record

That is no longer a simple fan-out job.

This is when you move from sync into repair or rebuild:

  • use index-contract drift or reconcile when you need posture first
  • use backfill when the live index is still trustworthy and just needs repair
  • use managed reindex when the contract changed or the live index no longer deserves trust

A Phoenix context shape that stays honest

The clean shape is still:

  • the owning context persists the original change
  • the owning context decides whether there is fan-out work
  • the context chooses the follow-up sync mode or operator path

For example, if posts own the search document but authors affect post documents:

  1. Accounts updates the author
  2. Accounts or a small orchestration boundary identifies affected posts
  3. that boundary syncs those posts explicitly

The exact module split can vary. The important invariant is that web modules still do not own this logic.

Picking the right follow-up path

The choice between inline and durable (Oban) execution comes down to two questions: how large is the blast radius (how many rows the change affects), and how much request latency can the calling request tolerate.

Small blast radius, latency-tolerant caller

Good fit:

  • a small, bounded number of affected rows
  • the caller benefits from knowing the update finished now
  • the request can absorb the extra latency of resolving and syncing in-process

Default:

  • inline follow-up with sync_mode: :inline

This returns {:ok, %{mode: :inline, status: :completed}} only after the affected documents are synced, so when the function returns you can truthfully say the work is done.

Larger blast radius, latency-sensitive request

Good fit:

  • many affected rows
  • request latency matters and the caller should not block on the fan-out
  • your app already treats Oban as normal production infrastructure

Default:

  • durable enqueue with sync_mode: :oban

This enqueues the internal RelatedWorker and returns {:ok, %{mode: :oban, status: :accepted}} immediately — before any document is synced. That changes what you are allowed to claim:

Truth you can say:

  • "the follow-up work is durably queued"

Truth you cannot say:

  • "all affected documents are searchable now"

What failures look like under :oban

When you choose sync_mode: :oban, the internal RelatedWorker — not your app code — maps each sync outcome onto Oban's retry/cancel contract. Knowing this mapping tells you which failures are permanent and which Oban will retry for you:

Outcome of the underlying syncRelatedWorker resultWhat happens
Success (:ok / {:ok, _}):okJob completes.
Backend HTTP 4xx (e.g. bad request){:cancel, {:http_error, status}}Permanent — Oban cancels the job, no retry. A 4xx is a client-side problem retrying will not fix.
Backend HTTP 5xx or generic error{:error, reason}Transient — Oban retries with backoff up to max_attempts: 8 (the worker default).
Invalid schema, unknown fan-out, or job args that do not decode (including a document id the document id field's type cannot cast or the repo's adapter cannot dump, such as "abc" for an integer key or for a :binary_id key on Postgres){:cancel, {:invalid_job, reason}}Permanent — the job can never succeed, so it is cancelled rather than retried.
The owner's search_records/2 returns something other than a list{:cancel, {:invalid_job, :invalid_search_records}}Permanent — an app bug no retry fixes. Fix search_records/2, then retry the cancelled job (for example from Oban Web).
None of the job's triggers load (deleted or excluded by search_records/2):okJob completes without calling the resolver.

You do not write or configure this mapping; the library owns it. Your resolver and context stay focused on finding and syncing the right records.

Unbounded or uncertain blast radius

Good fit:

  • imports
  • large migrations
  • staged operator work
  • situations where you cannot confidently bound the affected rows up front
  • situations where you want to inspect before cutover

Default:

  • manual flow, backfill, or managed reindex

When you cannot answer "how many rows will this touch?", neither sync_mode: :inline nor sync_mode: :oban is the right reach — move to a deliberate operator path instead.

Deletes are their own category

Deletes are where many libraries get hand-wavy. Scrypath should not.

If a source row is gone, a later async delete job may not be able to reload it. That is normal. The safe pattern is:

  • carry enough identity to delete the document directly from the index
  • do not depend on reloading the deleted source row later

When stale deletes still appear:

  • inspect failed work
  • inspect reconcile and drift posture
  • decide whether one explicit retry is enough or whether the index needs broader repair

In SaaS apps, not every related-data change is cosmetic.

Sometimes the changed data affects who should be able to see the document at all.

Examples:

  • a record moves tenants
  • a team membership change affects searchable visibility
  • a role or account-status change changes which rows should appear

Treat these as higher-risk related-data events:

  • be explicit about the tenant boundary in app code
  • be explicit about which source records are affected
  • prefer a repair or rebuild workflow when the visibility model changed broadly

Scrypath can help with sync, search, and recovery. It should not pretend index prefixes alone are your authorization model.

When to choose backfill versus reindex

Use this shortcut:

  • backfill when the live index contract is still right and the data just needs repair
  • reindex when the contract changed or you no longer trust the live index

Examples where backfill is usually right:

  • a queue outage delayed some updates
  • a bounded set of related-data fan-out jobs failed
  • the document shape is unchanged and you trust the current index settings

Examples where reindex is usually right:

  • projected fields changed broadly
  • filterable or faceting declarations changed
  • settings changed in a way that implies a rebuild
  • you cannot confidently identify all affected source records

Both workflows build documents the same way Oban sync does: each batch is loaded with the schema's preload: associations, and a schema's search_records/2 decides which rows are searchable. They differ in what happens to the rows search_records/2 leaves out:

  • a backfill writes to the live index, so it deletes those ids and counts them in removed
  • a managed reindex writes to a fresh index, so it counts them in omitted and deletes nothing

A backfill only touches the rows it visits. It is not a whole-index prune: documents for rows deleted outside Scrypath, or for rows outside the :query scope, stay in the index. Use Scrypath.reconcile_sync/2 to find that drift, and a managed reindex when you need the index rebuilt from scratch.

Primary keys and :query

Composite primary keys are supported. Backfill pages on the full key, visits each row once, and reports each batch's last_primary_key as a keyword list such as [org_id: 1, id: 7]. Declare composite primary-key fields in the same order as the columns of the database constraint, so the constraint's index serves the backfill ordering.

:query decides which rows are visited. Its where and join clauses apply; its order_by, limit, offset, select and preload are ignored, because backfill owns paging, projection and preloading. A :query must not fan out rows. When a join repeats a source row, the duplicates take up batch slots: backfill drops repeats within a batch, so batches come back smaller than batch_size and the database does extra work. Scope with where or an exists subquery instead of a join that can match several rows.

A practical decision tree

Ask these questions in order:

  1. Did the changed row own the document directly?
  2. If not, can I clearly query the affected source records?
  3. Is the blast radius small enough for normal sync, or is this now repair work?
  4. Do I still trust the live index contract?
  5. What truth do I need to be able to say when this function returns?

That yields the usual outcomes:

  • direct sync
  • explicit fan-out sync
  • queued fan-out sync
  • backfill
  • managed reindex

What Scrypath should stay opinionated about here

These are the least-surprise defaults:

  • contexts own orchestration
  • the library owns execution
  • related-data propagation is explicit
  • request-edge helpers do not own fan-out logic
  • use Scrypath stays metadata-only
  • recovery is public and documented

That split is the heart of sync_related/3: contexts own orchestration — your code decides when to fan out, which records are affected, and which mode to run — while the library owns execution — Scrypath runs the resolver, dispatches the internal RelatedWorker under :oban, and maps failures onto the retry/cancel contract. Neither side reaches into the other.

The tempting alternative is callback magic. That shape feels easy until the first production drift incident. Then it becomes hard to reason about, hard to test, and hard to repair.