Skip to main content
← Back to Patterns

Publish related BigQuery tables as one consistent release

By Ivan Richter LinkedIn

Last updated:

9 min read

In brief

Publish related BigQuery tables in one DML transaction when the change fits. Use immutable releases when readers need consistency across separate queries.

  • Validate the related rows together and prevent an older publisher from replacing newer data.
  • Have multi-query readers select one release ID and reuse it.
On this page

An order model finishes rebuilding before its order-line model. Both eventually pass their checks.

During the gap, though, a reader joins the new orders to the previous lines. The pipeline validated two tables and never published a coherent result.

For a bounded set of existing BigQuery tables, we’d first consider one DML transaction that replaces the related scope together.

If building or keeping complete generations fits better, publish immutable generation data through a single accepted release identifier. Readers then use that identifier for every query that needs one release.

First identify which queries must share a result. A single join, a dashboard issuing several queries, and a multi-step export don’t necessarily need the same mechanism. A manifest called current can’t keep independent queries on the same generation unless the reader carries that choice between them.

Define the consistency group

List the tables whose relationships must hold together and the scope of the replacement. An order header and its lines are an obvious group. Two unrelated daily metrics that share an orchestrator needn’t wait for each other.

Then define what makes a candidate complete. In the order example, each line must belong to a candidate order, and line identities must be unique at their declared grain. Order totals must reconcile with the lines that count under the model’s rules.

The source cutoff and transformation version belong to the group too. Two individually fresh tables can still describe different source populations.

Build and validate the exact candidate that publication will expose. A successful assertion against a mutable candidate table stops being evidence if another run can overwrite it before publication. Freeze the candidate’s inputs and outputs, or run the validation and reads under a supported consistent boundary.

Take extra care with external sources. BigQuery transactions don’t promise a consistent view of changing external data.

An empty candidate can be valid. Completeness comes from the declared source scope and its controls, and a blanket at-least-one-row rule would reject it.

A full replacement also needs permission to remove rows that existed in the previous release but are absent from the accepted candidate.

Use one DML transaction when the scope fits

BigQuery supports atomic mutations across multiple tables and snapshot isolation inside a transaction. Transactions support DML against existing tables, but not creating or dropping permanent entities. A sequence of permanent table replacements or view-definition changes isn’t one transaction.

This script replaces one scope of orders and lines from immutable candidate rows. It assumes the release manifest’s ready state means the group’s checks have passed. It also assumes the control table has exactly one publication row per scope, managed only by the publisher. Capturing the expected publication revision for this candidate stops an older worker from overwriting a release that advanced in the meantime.

BEGIN
  BEGIN TRANSACTION;

  ASSERT (
    SELECT COUNT(*) = 1
    FROM control.release_manifest
    WHERE scope_id = @scope_id
      AND release_id = @candidate_release
      AND status = 'ready'
  ) AS 'Candidate release is not ready';

  ASSERT (
    SELECT COUNT(*) = 1
    FROM control.publication_state
    WHERE scope_id = @scope_id
  ) AS 'Publication state must have one row';

  UPDATE control.publication_state
  SET publication_revision = publication_revision + 1,
      release_id = @candidate_release
  WHERE scope_id = @scope_id
    AND publication_revision = @expected_revision;
  ASSERT @@row_count = 1 AS 'Publication base changed';

  DELETE FROM mart.orders WHERE scope_id = @scope_id;
  INSERT INTO mart.orders (scope_id, order_id, total)
  SELECT scope_id, order_id, total
  FROM candidate.orders
  WHERE scope_id = @scope_id AND release_id = @candidate_release;

  DELETE FROM mart.order_lines WHERE scope_id = @scope_id;
  INSERT INTO mart.order_lines (scope_id, order_id, line_no, amount)
  SELECT scope_id, order_id, line_no, amount
  FROM candidate.order_lines
  WHERE scope_id = @scope_id AND release_id = @candidate_release;

  COMMIT TRANSACTION;
EXCEPTION WHEN ERROR THEN
  ROLLBACK TRANSACTION;
  RAISE;
END;

The datasets and tables must already exist with compatible schemas and locations. Bind the parameters through the client. The candidate release identifies fixed rows in both candidate tables.

The publisher must also control every other writer to the served scope. A separate append or repair path can invalidate the release after this transaction commits.

ASSERT fails on false or null. The affected-row check immediately follows the control-row UPDATE, because BigQuery’s row-count variable describes the preceding DML statement. A zero-row update is a failed publication precondition, even if the SQL statement itself succeeded.

The error handler rolls back and rethrows, so the orchestrator sees the failure.

Sessions behave differently. Inside one, an unhandled error can leave a session-mode transaction active. Handle the rollback in the script itself, and don’t let a caller leave an abandoned transaction open. The script assumes it begins its own transaction.

Treat this as illustrative SQL until it has passed an isolated BigQuery execution check with your schemas, permissions, partition predicates, and client error handling. It isn’t a deployed publisher. The DML reference defines the target-column and query forms used here.

Treat an older publisher as a separate failure

An atomic commit can still publish an outdated candidate. A slow candidate can finish after a newer one has already become current, then replace it coherently with older data.

Use one serialized publisher or a checked publication revision, plus a stated policy for which candidate may follow the current state.

In the script, advancing the control row is part of the same transaction as the data replacement. If another release has changed the expected revision, re-evaluate this candidate. Don’t just fetch the new revision and retry the stale one.

Keep that revision separate from the release identifier. A deliberate rollback may point back to a previously served generation. The publication revision still has to advance. Otherwise an old worker that remembers generation one becomes eligible again when the pointer returns to it.

BigQuery can cancel conflicting mutating transactions. Transaction retry belongs in the recovery path. A retry after a conflict still runs the candidate’s readiness and expected-base checks.

Recover the job’s outcome before deciding what to submit next. It’s most urgent when the client stopped waiting before learning whether the commit succeeded.

Keep candidate construction outside a long-lived publication lock where possible. The critical step should only select and expose an already validated result. If replacing the data itself makes that step too large or disruptive for the workload, generation publication may fit better.

Build immutable generations when readers can select one

In a generation design, every related output has a release identifier or an equivalent immutable table reference. Build the candidate orders and lines under the same release, validate the complete group, and only then make it selectable. A failed second model then leaves the previous release selected.

The write path and permissions have to enforce immutability. A release label on rows that another job can update is just metadata. Reusing a release ID for a retry with different bytes breaks immutability too. Keep candidate attempts distinct until one fixed result is accepted.

Readers first obtain the accepted release ID, then include it in every related query. For a custom export, that can be an ordinary parameter passed from the first step to the rest of the job. For a BI tool, verify that one refresh can carry a fixed release value into all of its queries. A separate current-release lookup inside each view doesn’t do that.

Other inputs can change the result’s interpretation. Pinning orders and lines while reading a mutable currency table, identity map, or product classification can still change the answer between steps. A generation identifier has no effect on a lookup the query never ties to it. Either include those inputs in the consistency group or let the output contract accept their independent versions. Review the consumer’s dependency graph, including helper views, before deciding that the group is complete.

Treat an unavailable pinned release as an error. If cleanup removed one output, returning an empty table can look like a valid zero. Falling back to current can combine the first half of an older export with the second half of a newer one. Check that the requested release is readable as a complete group with the schema the reader expects. If the reader must restart with a different release, it restarts the entire consistency scope. A small client-level acceptance test should exercise both that refusal and the normal refresh.

For example, an export reads generation-one orders, then publication advances to generation two. Its next query must still request generation-one lines. Looking up current again could combine the old orders with newer lines, even though the manifest and both generations are individually valid.

The client reads the accepted release ID once and binds that same value as @release_id in both requests. Here, generations.orders and generations.order_lines keep immutable rows for each release:

-- First request
SELECT order_id, total
FROM generations.orders
WHERE scope_id = @scope_id AND release_id = @release_id;

-- Second request, after publication may have advanced
SELECT order_id, line_no, amount
FROM generations.order_lines
WHERE scope_id = @scope_id AND release_id = @release_id;

When a consumer can’t pin a generation, adapt the serving boundary.

A single prepared relation or one server-side query may fit its use, and a transaction-aware client can keep multiple reads inside a supported read transaction. Otherwise independent refreshes can observe different accepted releases. More publication metadata won’t synchronize them.

Match the reader guarantee to the release mechanism

An atomic replacement protects readers from a partially committed group, but it doesn’t freeze that group’s contents across two separate queries. A reader can fetch orders before a commit and lines after it, and each query still observes a valid committed database state.

A PostgreSQL repeatable-read transaction keeps one snapshot across those queries, while read committed ordinarily takes a fresh snapshot for each statement. A BigQuery reader needs its own supported transaction or pinned generation. Similar transaction syntax in another database won’t tell you how its client keeps the session and read boundary.

Generation retention is part of that scope. A pinned reader needs its release to stay available for the duration of the work and any supported retry. The cleanup policy must protect active readers or keep generations for a stated maximum reader lifetime. Deleting generation one’s lines can break a reader still pinned to that release, while the current pointer remains perfectly valid.

Test where the group can split

Before relying on the release mechanism, check that each of these cases behaves as described:

  • A failed second mutation leaves both previously served tables unchanged.
  • A reader held open across a successful commit shows whether its queries share the intended read boundary.
  • An unready candidate is rejected.
  • Of two publishers built from the same base revision, only one succeeds.
  • A stale candidate stays rejected even after a deliberate rollback points at an older release.
  • With generation publication, a consumer keeps its original release when the pointer changes between two of its queries. The same holds for queries that go through helper views.
  • A pinned release that has been made unavailable fails with an error.
  • Readiness and immutability come from the real permissions and write paths. A manually seeded ready flag doesn’t test them.

A successful dry run doesn’t replace these tests: multi-statement dry runs stop at documented points around control flow and dynamic SQL. Inspect what was validated, then run bounded failure cases in an isolated dataset.

More in this domain: Data

Browse all

Related patterns