The lakehouse promise is most useful when it is concrete: batch jobs should publish immutable table versions, consumers should see either the old result or the new result, and maintenance should not require an analyst to understand thousands of object paths. Apache Iceberg supplies table snapshots, hidden partitioning, and metadata; Amazon EMR supplies Spark execution. A sound Bronze/Silver/Gold design still needs explicit quality checks and an operational lifecycle.
Separate layers by durability and meaning
Bronze preserves source records and ingestion context. Silver enforces a schema, deduplicates business keys, and adds conformed dimensions. Gold contains query-oriented aggregates or features with a declared consumer contract.
Keep the layers in separate catalog databases and S3 prefixes:
s3://example-lake/bronze/
s3://example-lake/silver/
s3://example-lake/gold/
Do not call a batch successful because Spark wrote files. Each layer needs a published snapshot, data-quality metrics, and the run identifier that produced it. The run identifier should be a table column in Bronze and part of job-level audit metadata in all layers.
Create an Iceberg table with hidden partitions
An EMR Spark catalog can use the AWS Glue Data Catalog and an S3 warehouse:
CREATE NAMESPACE IF NOT EXISTS glue.lakehouse;
CREATE TABLE glue.lakehouse.orders (
order_id STRING,
customer_id STRING,
order_ts TIMESTAMP,
order_status STRING,
amount_cents BIGINT,
ingest_date DATE,
source_run_id STRING
)
USING iceberg
PARTITIONED BY (days(order_ts), truncate(32, customer_id))
TBLPROPERTIES (
'format-version' = '2',
'write.format.default' = 'parquet',
'write.parquet.compression-codec' = 'zstd',
'write.distribution-mode' = 'hash'
);
Spark configuration selects the catalog:
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("iceberg-lakehouse-batch") \
.config(
"spark.sql.extensions",
"org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions"
) \
.config("spark.sql.catalog.glue",
"org.apache.iceberg.spark.SparkCatalog") \
.config("spark.sql.catalog.glue.catalog-impl",
"org.apache.iceberg.aws.glue.GlueCatalog") \
.config("spark.sql.catalog.glue.warehouse",
"s3://example-lake/warehouse") \
.getOrCreate()
This configuration uses Iceberg’s Glue catalog implementation and an S3 warehouse. Keep the EMR release, Spark runtime, AWS SDK, and Iceberg library bundle compatible and test them together during upgrades.
Hidden partitioning means users query order_ts without knowing that the physical partition transform is daily. That gives Iceberg room to evolve the layout.
Partition evolution is a schema operation with a cost
Start with a transform that aligns with filter clauses and file sizing. A table with years of daily data can accumulate excessive manifest work if each daily partition is very small. If daily writes become too granular, use months for historical rows or add a transformation after measuring scans.
ALTER TABLE glue.lakehouse.orders
ADD PARTITION FIELD months(order_ts);
ALTER TABLE glue.lakehouse.orders
DROP PARTITION FIELD days(order_ts);
Dropping an old partition field changes how new data is written. Existing files remain valid under metadata that records their historical partition specifications. Do not interpret evolution as an immediate rewrite.
Schema changes also require care. Add nullable columns before consumers depend on them. Renaming can be safe in Iceberg metadata, but downstream Athena views, BI models, and contracts may still use the old name. Removing a required column is an application migration, not a simple DDL statement.
Merge incoming records transactionally
An idempotent Spark merge is a good way to create current Silver state:
MERGE INTO glue.lakehouse.orders AS target
USING (
SELECT *
FROM glue.lakehouse.bronze_orders
WHERE source_run_id = '20220628-run-01'
) AS source
ON target.order_id = source.order_id
WHEN MATCHED
AND source.order_ts >= target.order_ts
THEN UPDATE SET
target.customer_id = source.customer_id,
target.order_ts = source.order_ts,
target.order_status = source.order_status,
target.amount_cents = source.amount_cents,
target.source_run_id = source.source_run_id
WHEN NOT MATCHED THEN INSERT *;
If duplicate keys exist in the source, the merge can be ambiguous or last-writer dependent. Deduplicate the staging relation by (order_id, updated_at) first, and fail if tie-breaking remains unclear. A replay of the same run should produce no extra records, but it can still create a new snapshot; idempotency is a data property, not a promise of identical metadata.
Gold tables are products, not views by habit
Materialize Gold when multiple teams need the same grain, the computation is expensive, or SLOs require stable files. A view is suitable for cheap transformations and exploratory semantics, but it couples query cost and availability to the underlying table at read time.
CREATE TABLE glue.lakehouse.daily_revenue
USING iceberg
AS
SELECT
CAST(order_ts AS DATE) AS revenue_date,
SUM(amount_cents) AS revenue_cents,
COUNT(*) AS order_count
FROM glue.lakehouse.orders
WHERE order_status = 'settled'
GROUP BY CAST(order_ts AS DATE);
For daily incremental refresh, prefer a run-scoped replacement or merge for affected partitions. Delete and append in the same application is a sequence of commits, so define which snapshot represents “complete” for consumers that read repeatedly.
Time travel and controlled rollback
Snapshot IDs make diagnosis possible:
SELECT * FROM glue.lakehouse.orders.history;
SELECT * FROM glue.lakehouse.orders.snapshots;
SELECT COUNT(*), SUM(amount_cents)
FROM glue.lakehouse.orders
VERSION AS OF 382901234567890;
Inspecting a snapshot is read-only. Rolling back the current metadata pointer is an operational change and should be treated as such:
CALL glue.system.rollback_to_snapshot(
table => 'lakehouse.orders',
snapshot_id => 382901234567890
);
Before rollback, confirm that no downstream job has already consumed newer data and that returning to the old snapshot is semantically acceptable. A bad write after downstream publication can require forward correction rather than rollback because consumers may not travel back.
Compact, expire, and remove safely
Every batch can create small files. Table maintenance should be scheduled independently of data production:
CALL glue.system.rewrite_data_files(
table => 'lakehouse.orders',
strategy => 'binpack',
options => map('target-file-size-bytes', '268435456')
);
CALL glue.system.rewrite_manifests('lakehouse.orders');
CALL glue.system.expire_snapshots(
table => 'lakehouse.orders',
older_than => TIMESTAMP '2022-06-01 00:00:00',
retain_last => 14
);
The retention count is an important recovery boundary. Snapshot expiration removes eligibility for later time travel, and orphan-file cleanup removes unreferenced objects. Do not run orphan deletion concurrently with active writers. A conservative process waits several times longer than the maximum writer duration and validates metadata references first.
Track these values weekly:
- average and p95 data-file size;
- files and manifests per snapshot;
- commits per hour and commit retry rate;
- snapshot retention window;
- orphan object count and bytes;
- Athena scan bytes per representative query.
A practical file target is 128 to 512 MiB. Alert if more than 10 percent of active files are below 32 MiB or if the manifest list grows materially while row volume remains stable.
Athena and Spark read paths
Athena and Spark can query the same Iceberg table, but they are independent compute engines. Use Glue catalog metadata consistently and avoid manually changing table properties. Test filter pruning, time travel syntax, and delete-file behavior in the exact engine versions used in production.
Athena should be given an access pattern, not merely permissions. A dashboard that scans an entire Gold table is a cost and performance defect. Partition-aligned predicates and small curated Gold tables reduce scan bytes and concurrency pressure.
Failure and recovery lifecycle
On a failed batch:
- Stop or let the failed job exit; do not publish a partial catalog pointer.
- Find the attempted
source_run_idand all created Iceberg snapshots. - Decide whether the snapshot is valid by reconciling counts and aggregate totals.
- If valid, publish downstream dependencies from that snapshot.
- If invalid, roll forward with a correction or roll back only when no dependent reader has committed to the newer version.
- Rerun into a new audit ID and retain old snapshots within the policy window.
spark-submit \
--conf spark.sql.catalog.glue=org.apache.iceberg.spark.SparkCatalog \
s3://example-code/build_silver.py \
--source-table glue.lakehouse.bronze_orders \
--target-table glue.lakehouse.orders \
--run-id 20220628-retry-02
Iceberg gives the pipeline precise metadata boundaries, but operational discipline still decides recovery. Keep schema, partition, snapshot, and retention changes in reviewed automation, then measure their effect on file count, scan bytes, commit latency, and recovery time.