6 minute read

Apache Iceberg adds table semantics to files in Amazon S3. A Flink application can continuously write immutable data files, checkpoint their state, and publish a new Iceberg snapshot when the associated checkpoint commits. Readers then choose a consistent snapshot rather than observing partially written files.

The important design question is not how to create many Parquet objects. It is how to balance commit freshness, file size, partition pruning, table metadata, and recovery.

Flink to Iceberg commit and maintenance lifecycle

Table and partition design

Start from query filters and data distribution. Iceberg hidden partitioning means queries use source columns while the table maintains partition transforms. A common event table is partitioned by coarse day or hour, then sorted by a second field if file-level skipping benefits.

CREATE TABLE glue.analytics.checkout_events (
  event_id     STRING,
  account_id   STRING,
  region       STRING,
  amount_cents BIGINT,
  event_time   TIMESTAMP(6),
  ingested_at  TIMESTAMP(6),
  payload      STRING
)
USING iceberg
PARTITIONED BY (days(event_time), bucket(32, region))
TBLPROPERTIES (
  'format-version' = '2',
  'write.format.default' = 'parquet',
  'write.target-file-size-bytes' = '134217728',
  'commit.retry.num-retries' = '5',
  'history.expire.min-snapshots-to-keep' = '100',
  'history.expire.max-snapshot-age-ms' = '86400000',
  'write.distribution-mode' = 'hash'
);

Do not copy every frequently filtered column into the partition expression. Very high-cardinality identity partitions create a metadata explosion. Iceberg stores min/max statistics for columns in files, which often provides useful pruning without partitioning.

Day partitions are usually a good starting point. Hour partitions increase directory and metadata cardinality, but may be justified for short retention and narrow incident queries. A bucket(32, region) expression usually has little value if there are only a few regions; the example is illustrative and should be changed from measured query access patterns.

AWS Glue catalog

The Flink SQL catalog can point to AWS Glue. Region, warehouse location, and IAM access must be aligned:

catalogs:
  - name: glue
    type: iceberg
    property-version: 1
    catalog-impl: org.apache.iceberg.aws.glue.GlueCatalog
    warehouse: s3://company-data-lake/warehouse
    io-impl: org.apache.iceberg.aws.s3.S3FileIO
    client.region: us-east-1

Flink runtime packaging is version-sensitive. Match the Flink, Flink Iceberg runtime, Iceberg, Hadoop filesystem, and AWS SDK components. Avoid placing overlapping AWS SDK and Hadoop classes on the classpath; shaded connector packages can otherwise produce NoSuchMethodError or credential-provider conflicts.

Grant the application role:

  • glue:GetDatabase, GetTable, UpdateTable, and required partition or catalog calls;
  • S3 list, get, put, and delete on the warehouse prefix;
  • KMS decrypt and encrypt if a customer-managed KMS key protects the bucket.

Use S3 bucket policy and IAM as two layers, and keep development roles from writing production warehouse paths.

A Flink SQL pipeline can read an existing Kafka or MSK source and append to the table:

CREATE TABLE checkout_source (
  event_id STRING,
  account_id STRING,
  region STRING,
  amount_cents BIGINT,
  event_time TIMESTAMP(3),
  payload STRING,
  WATERMARK FOR event_time AS event_time - INTERVAL '30' SECOND
) WITH (
  'connector' = 'kafka',
  'topic' = 'checkout-events',
  'properties.bootstrap.servers' = '${MSK_BOOTSTRAP_SERVERS}',
  'properties.group.id' = 'checkout-iceberg-v1',
  'scan.startup.mode' = 'group-offsets',
  'format' = 'json'
);

INSERT INTO glue.analytics.checkout_events
SELECT
  event_id,
  account_id,
  region,
  amount_cents,
  event_time,
  CURRENT_TIMESTAMP,
  payload
FROM checkout_source;

CURRENT_TIMESTAMP is nondeterministic on replay. Use it only for an intentionally processing-time audit column. Stable event data belongs in event_time; if replay must be reproducible, derive ingested_at in the source event.

For DataStream applications, use the Iceberg sink builder and specify a stable operator UID:

FlinkSink.forRowData(input)
    .table(table)
    .tableLoader(tableLoader)
    .distributionMode(DistributionMode.HASH)
    .writeParallelism(16)
    .uidPrefix("checkout-iceberg-v1")
    .append();

Exact APIs change across compatible Flink and Iceberg versions, so use the connector version’s signature at build time. Keep the UID prefix stable across normal restarts. The sink state tracks pending files and commits with checkpoints.

Commits and reader consistency

During a checkpoint, writers finalize data and manifest files, and the committer publishes the set as an Iceberg snapshot. A failed checkpoint does not publish its incomplete transaction. On restore, Flink rewinds the Kafka source and reprocesses records while the sink discards or cleans up uncommitted files.

Iceberg gives readers a snapshot-consistent view:

  • a query before commit reads the previous snapshot;
  • a query after commit reads the new complete snapshot;
  • one table scan does not mix snapshots unless the engine chooses otherwise.

This is not the same as every consumer seeing zero-latency data. Checkpoint frequency, sink commit duration, catalog latency, and query start time all contribute. If checkpoints run every five minutes, measure end-to-end visibility as at least that plus connector commit time, even when individual records arrive instantly.

Two writers committing to the same table can conflict. For append-only writes, Iceberg can retry compatible commits. Conflicting maintenance or schema operations may require serialization. Assign clear table ownership and coordinate streaming, compaction, and schema migration jobs.

Small files and checkpoints

Frequent checkpoints expose many small files. Suppose 16 writers each close a 2 MB file per two-minute checkpoint. That is about 480 files per hour, excluding retries and partitions. Millions of small files increase listing, planning, and metadata merge cost even though the bytes may be modest.

Countermeasures have trade-offs:

  • longer checkpoints improve file size but worsen data freshness and replay;
  • higher target file size improves scans but may hold more bytes in open writers;
  • write parallelism aligned with partitions reduces cross-partition files but can underuse compute;
  • rolling writers close files during long checkpoints but can increase file count;
  • compaction combines files but adds read, write, and snapshot cost.

Measure files committed per checkpoint and average Parquet size. A useful initial alert is median file size below 16 MiB or file count growth above the forecast by 25%. The correct threshold depends on object count, table size, and query engine.

Compaction and snapshot expiration

Rewrite manifests and small data files in scheduled jobs after the stream is stable:

CALL glue.system.rewrite_data_files(
  table => 'analytics.checkout_events',
  strategy => 'binpack',
  options => map(
    'target-file-size-bytes', '268435456',
    'min-input-files', '5'
  )
);

CALL glue.system.rewrite_manifests(
  table => 'analytics.checkout_events',
  use_starting_sequence_number => true
);

Procedure availability and names vary by Iceberg engine and version. Confirm in the selected engine before production use.

Expire old snapshots separately from orphan-file cleanup:

CALL glue.system.expire_snapshots(
  table => 'analytics.checkout_events',
  older_than => TIMESTAMP '2021-11-02 00:00:00.000',
  retain_last => 100
);

Snapshot expiration reduces metadata reachability. It must preserve every snapshot required by time travel, audits, and long-running readers. Orphan cleanup can permanently delete unreferenced files, so configure a safety window longer than the maximum checkpoint and writer retry period.

Read consistency and replay

Flink recovery restores the last successful checkpoint and Kafka offsets. A data file that exists on S3 but is not referenced by an Iceberg snapshot is not table data. Later cleanup may remove it. A completed snapshot referenced by the catalog is visible and will not be rolled back by a Flink task restart.

There are two consequences:

  1. A source replay can rewrite rows after a sink commit only when the output checkpoint was incomplete.
  2. A Flink checkpoint and sink transaction need exactly-once configuration for one append per source position.

Test by terminating a writer while it has open data files. Then validate:

  • no uncommitted data is visible;
  • source lag returns to normal after restore;
  • snapshot row count equals the expected input count;
  • orphan files are bounded and removable only after the safety period.

Add event_id uniqueness reconciliation when downstream contracts need business exactly once. Iceberg tables do not enforce a primary key on every append.

Operational dashboard

Track:

  • source lag by partition and Flink checkpoint age;
  • commit latency from checkpoint completion to Glue snapshot;
  • data bytes and files per snapshot;
  • median and p95 Parquet file size;
  • manifest count and metadata file bytes;
  • failed or retried Iceberg commits;
  • open writers and checkpoint-to-publish latency;
  • query planning duration and S3 LIST request volume.

A starting SLO could be: 95% of committed records visible within five minutes; at least 95% of data files above 32 MiB after compaction; checkpoint success at least 99.9%; and no snapshot conflict unresolved for more than 15 minutes. Tune these numbers to freshness and cost requirements.

Release and recovery checklist

Before enabling writes:

  1. Run DDL in staging and inspect the generated Iceberg metadata.
  2. Verify Glue and S3 IAM with allowed and denied prefixes.
  3. Load one day of skewed production-like events.
  4. Confirm a query sees either the old or complete new snapshot.
  5. Force a writer failure and reconcile row and event counts.
  6. Run compaction and measure scan improvement.
  7. Set expiry windows after backup, audit, and time-travel review.

Streaming to Iceberg is a transaction protocol around object files. Correctness comes from matching Flink checkpoints to Iceberg commits; cost and query health come from controlling the lifecycle of every resulting file and snapshot.