8 minute read

An Iceberg lakehouse makes table state a versioned set of metadata and data files. Dataproc provides Spark, GCS provides durable object storage, and a metastore provides the durable mapping from a table name to its current Iceberg metadata. That architecture is useful only when writers use one catalog policy, readers understand snapshots, and maintenance has an explicit retention and cost model.

Apache Iceberg lakehouse on Dataproc and GCS

Choose one catalog authority

Iceberg tables consist of a metadata location, manifests, manifest lists, and data files. The catalog stores the current metadata pointer; the object store stores the objects. Two catalog definitions that point at the same GCS prefix are still two coordination domains, and both can publish incompatible changes.

On Google Cloud, common options include:

  • the Spark-initialized Hive metastore, when existing Hive workloads and governance are primary;
  • an Iceberg HadoopCatalog for an isolated lake whose namespace can be represented directly in the warehouse;
  • a custom or service catalog integrated with the organization’s metadata and access control;
  • an external BigLake BigQuery relationship, used deliberately rather than as an implicit second writer.

For an environment centered on Dataproc, a Dataproc Metastore-backed catalog provides a managed Hive API. The exact metastore implementation and Iceberg Spark catalog class must be validated against the Dataproc and Iceberg runtime versions. The following Spark configuration illustrates a catalog in Dataproc:

spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions
spark.sql.catalog.lake=org.apache.iceberg.spark.SparkCatalog
spark.sql.catalog.lake.type=hive
spark.sql.catalog.lake.uri=thrift://DATAPROC_METASTORE_HOST:9083
spark.sql.catalog.lake.warehouse=gs://example-iceberg/warehouse

If a HadoopCatalog is selected instead, store the table namespace beneath a controlled warehouse:

spark.sql.catalog.lake=org.apache.iceberg.spark.SparkCatalog
spark.sql.catalog.lake.type=hadoop
spark.sql.catalog.lake.warehouse=gs://example-iceberg/warehouse

The GCS service account needs object operations and, for a metastore catalog, only the required metastore network access. IAM should not grant broad object deletion to every analyst simply because one ingestion service performs expiration.

Create a Dataproc runtime with compatible Iceberg JARs

Iceberg’s Spark runtime must match Spark’s Scala binary version. A mismatch can fail at class loading rather than at submit time. Put the runtime JAR, its checksum, and the Spark/Dataproc image version in one release.

gcloud dataproc jobs submit pyspark \
  gs://example-code/iceberg/create_orders.py \
  --region=us-central1 \
  --cluster=lakehouse-cluster \
  --jars=gs://example-code/deps/iceberg-spark-runtime-3.1_2.12-0.14.1.jar \
  --properties='spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions,spark.sql.catalog.lake=org.apache.iceberg.spark.SparkCatalog,spark.sql.catalog.lake.type=hadoop,spark.sql.catalog.lake.warehouse=gs://example-iceberg/warehouse'

This is a versioned example, not a recommendation to download an arbitrary JAR into an arbitrary image. Test the complete tuple of Dataproc image, Spark, Scala, Iceberg runtime, GCS connector, and any BigQuery connector during an upgrade.

Define schema and hidden partitioning

Create namespaces and a table with DDL:

CREATE NAMESPACE IF NOT EXISTS lake.silver;

CREATE TABLE lake.silver.orders (
    order_id STRING NOT NULL,
    customer_id STRING NOT NULL,
    order_ts TIMESTAMP NOT NULL,
    status STRING,
    amount_cents BIGINT,
    source_version STRING,
    source_run_id STRING
)
USING iceberg
PARTITIONED BY (months(order_ts), bucket(32, customer_id))
TBLPROPERTIES (
    'format-version' = '2',
    'write.format.default' = 'parquet',
    'write.parquet.compression-codec' = 'zstd',
    'write.distribution-mode' = 'hash'
);

Hidden partitioning allows a query to filter on order_ts without knowing the physical month transform. It also allows the specification to evolve. A transform should be selected from observed query filters and write patterns:

  • day transform for date predicates with moderate daily volume;
  • month transform for smaller historical writes or append-oriented history;
  • bucket transform for a write or join key that otherwise creates small partitions;
  • no high-cardinality raw timestamp as an untransformed partition.

A daily specification over five years creates unnecessary manifests if most days contain a few records. A month specification may scan too much for a recent-day dashboard. Start with measured access patterns, then use partition evolution rather than treating the initial choice as permanent.

ALTER TABLE lake.silver.orders
ADD PARTITION FIELD days(order_ts);

-- Keep the old specification for existing data while new files follow both
-- specifications during the reviewed migration. Drop the old field only
-- after its scan and write consequences are understood.
ALTER TABLE lake.silver.orders
DROP PARTITION FIELD months(order_ts);

Evolution changes metadata. It does not rewrite existing files. Plan a table migration when both reader performance and write-file sizing require old data to move physically.

Schema evolution follows a consumer contract too. Add optional columns, set field IDs through Iceberg, and keep consumers compatible. Rename is represented in Iceberg metadata, but SQL views and BigQuery integration may not update automatically. Required-column deletion is an application migration, not cleanup.

Upsert with a deterministic source

An MERGE INTO transaction can represent a run-scoped current state. Deduplicate Bronze first:

from pyspark.sql import SparkSession, Window, functions as F

spark = SparkSession.builder.appName("orders-iceberg-upsert").getOrCreate()

bronze = spark.read.table("lake.bronze.order_events") \
    .where("source_run_id = '20220907-01'")

ranked = bronze.withColumn(
    "source_row",
    F.row_number().over(
        Window.partitionBy("order_id").orderBy(
            F.col("event_ts").desc(),
            F.col("source_version").desc(),
        )
    ),
).where("source_row = 1").drop("source_row")

ranked.createOrReplaceTempView("incoming_orders")
spark.sql("""
MERGE INTO lake.silver.orders AS target
USING incoming_orders AS source
ON target.order_id = source.order_id
WHEN MATCHED
 AND source.event_ts >= target.order_ts
THEN UPDATE SET
    customer_id = source.customer_id,
    order_ts = source.event_ts,
    status = source.status,
    amount_cents = source.amount_cents,
    source_version = source.source_version,
    source_run_id = source.source_run_id
WHEN NOT MATCHED THEN INSERT (
    order_id, customer_id, order_ts, status, amount_cents,
    source_version, source_run_id
) VALUES (
    source.order_id, source.customer_id, source.event_ts,
    source.status, source.amount_cents, source.source_version,
    source.source_run_id
)
""")

The source needs one deterministic winner per business key. Without it, a replay can choose rows in source scan order. The comparison timestamp protects late events, but semantic version and deletes must also be considered. Tombstone records generally require an explicit op=delete branch, otherwise the latest negative state cannot be represented.

An Iceberg commit is atomic at the table metadata pointer. The operation can still create a new snapshot after a replay, even if row values remain unchanged. Idempotency of content does not mean identical snapshot history.

Read snapshots and time travel

Inspect history before deciding to roll forward or back:

SELECT committed_at, snapshot_id, operation, summary
FROM lake.silver.orders.snapshots
ORDER BY committed_at DESC;

SELECT *
FROM lake.silver.orders
VERSION AS OF 8745016234702391001;

SELECT COUNT(*) AS row_count, SUM(amount_cents) AS total_cents
FROM lake.silver.orders
VERSION AS OF 8745016234702391001
WHERE order_ts >= TIMESTAMP '2022-09-01 00:00:00';

Time travel reads metadata and retained data files. It is not a permission bypass: principals still need the applicable GCS and catalog rights.

Rollback is a pointer operation:

CALL lake.system.rollback_to_snapshot(
    table => 'silver.orders',
    snapshot_id => 8745016234702391001
);

Do not roll back after downstream jobs have published the newer snapshot unless those products will also be invalidated. Often a forward correction produces a new transparent snapshot and is safer than making independently consumed systems travel backward.

Compact data and metadata

Each microbatch or small upsert can produce small files. Schedule independent maintenance and bind its resource envelope so it cannot starve interactive and batch jobs:

CALL lake.system.rewrite_data_files(
    table => 'silver.orders',
    strategy => 'binpack',
    options => map(
        'target-file-size-bytes', '268435456',
        'min-file-size-bytes', '67108864',
        'max-concurrent-file-group-rewrites', '8'
    )
);

CALL lake.system.rewrite_manifests(
    table => 'silver.orders'
);

For partition-aligned services, a sorted rewrite can improve scan locality but adds more CPU and shuffle. Pick the sort order only after measuring the main predicates and write cost.

Snapshot expiration defines history eligibility and storage retention:

CALL lake.system.expire_snapshots(
    table => 'silver.orders',
    older_than => TIMESTAMP '2022-08-01 00:00:00',
    retain_last => 30
);

Never expire snapshots and remove orphan files as an uncoordinated response to storage growth. First account for:

  • the maximum expected active writer;
  • downstream time-travel requirements;
  • delayed rollback and audit windows;
  • manifests still referenced by retained snapshots;
  • abandoned jobs that can continue writing older metadata.

An orphan cleanup must run after a safety interval longer than active writers and retries. A too-aggressive cleanup can delete files before a writer commits its metadata.

Let Spark and BigQuery read the same contract

Spark and BigQuery should consume a declared table semantic contract. They need not use the same files if interoperability cost or feature support makes that design weak. The options are:

  1. Register an Iceberg table through a supported BigLake or external-table integration, preserving one physical Iceberg table.
  2. Read BigQuery staging or serving tables into Spark with the BigQuery connector, then write Spark output to an Iceberg table.
  3. Publish from Iceberg to a BigQuery-managed serving table on a schedule.

For option two, keep the boundary explicit:

customers = (
    spark.read.format("bigquery")
    .option("table", "PROJECT_ID.analytics.customers")
    .option("filter", "status = 'active'")
    .load()
)

with_customers = spark.table("lake.silver.orders") \
    .join(customers, "customer_id", "left")

For BigQuery-to-Iceberg publication, add source_run_id, source snapshot identifiers, row count, and aggregate checks. The system should tell operators whether a lagging BigQuery result is from a known snapshot or an unknown partial transfer.

If BigQuery uses Iceberg-compatible metadata, still test support for delete files, schema evolution, hidden partition transforms, snapshots, and the exact Spark and BigQuery versions. “Can list the table” is not equivalent to “can safely query every supported table evolution.”

Cost and operational metrics

GCS request and storage costs are part of table design:

  • object bytes in live data files;
  • retained snapshots and unreferenced object bytes;
  • list and rewrite operations;
  • manifest count and size;
  • Dataproc worker hours for compaction;
  • Spark shuffle and write amplification;
  • BigQuery scan and copy/load cost.

Measure these each week:

live files / live rows
median and p95 data-file size
percentage of files below 32 MiB
manifests and manifests per snapshot
commit retry rate and commit latency
snapshot retention in bytes and days
orphan candidate bytes
scan bytes per representative query

A good maintenance budget ties to workload value. Compaction of a table read once per month can cost more than the scan it saves. Keep frequently read Gold tables at a tighter physical target than archival Bronze.

Failure and publication runbook

On a failed or suspicious load:

  1. Record the attempted source_run_id and the snapshot ID if committed.
  2. Compare row count and domain aggregates to the expected source.
  3. Read the table at the previous snapshot and the new snapshot side by side.
  4. Check delete, duplicate, and late-arrival behavior on a key set.
  5. If downstream consumers have not committed, roll back or forward-correct as the policy permits.
  6. If downstream publication already occurred, create a new correction snapshot and reconcile every derived product.
  7. Retain the failed run’s logs and metadata until the incident review closes.

Run the following health inventory before maintenance:

gcloud dataproc jobs submit pyspark \
  gs://example-code/iceberg/table_health.py \
  --region=us-central1 \
  --cluster=lakehouse-cluster \
  --jars=gs://example-code/deps/iceberg-spark-runtime-3.1_2.12-0.14.1.jar \
  --properties='spark.sql.catalog.lake.type=hadoop,spark.sql.catalog.lake.warehouse=gs://example-iceberg/warehouse,spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions' \
  -- --table=lake.silver.orders

The health job should report snapshots, file sizes, orphan candidates, and representative query scan metrics. Make expiration and orphan removal a separate, reviewed job with dry-run evidence. Lakehouse reliability is the catalog transaction plus the operational discipline around retention, not object count alone.

Release checklist

Before production:

  • pin the Dataproc/Spark/Scala/Iceberg/connector matrix;
  • prove one catalog authority and least-privilege GCS IAM;
  • test schema and partition evolution on a copy;
  • replay the same source_run_id without duplicate business rows;
  • read an old and current snapshot from Spark;
  • validate a supported BigQuery serving path;
  • interrupt a commit and verify the previous snapshot remains readable;
  • rehearse rollback versus forward correction;
  • run compaction and expiration under a storage budget.

An Iceberg table on GCS becomes a platform when its current pointer, physical layout, maintenance, and consuming systems are all versioned and observable.