Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

25.1 KB
Raw Blame

Design: Idempotency-Key Support for the Gravitino Iceberg REST Server

Field Value
Status Draft
Authors @laserninja
Created 2026-07-16
Module iceberg/iceberg-rest-server, iceberg/iceberg-common

1. Background

The Iceberg REST spec defines an optional Idempotency-Key header (UUIDv7) on all mutation endpoints (create/update/delete for tables, namespaces, and views). When present, the server must:

  1. Execute the mutation on first receipt and store the response.
  2. Return the stored response on subsequent retries with the same key.
  3. Advertise the key reuse window via idempotency-key-lifetime in GET /v1/config.

Without this, network failures and client retries can cause duplicate table/namespace/view creation or deletion.

1.1 Multi-Node Problem

Gravitino's Iceberg REST server can run as multiple replicas behind a load balancer. A purely in-memory cache (e.g., Caffeine) is node-local:

  • Retry hits different node: The second node has no record of the first execution and re-runs the mutation (duplicate side-effect).
  • Node crash: All cached responses are lost; retries execute again.

A production-grade solution requires shared, durable storage for idempotency records.

1.2 Prior Art

Apache Polaris introduced database-backed idempotency support in apache/polaris#3205 with a Postgres-backed IdempotencyStore SPI. Their design includes heartbeat-based liveness, executor ownership, crash reconciliation, and minimal response reconstruction. Gravitino can adopt a simplified version of this pattern that fits its existing relational backend and shorter mutation lifecycle.

Note that in Polaris idempotency is disabled by default and must be explicitly enabled. This design follows the same convention (see Section 6).

1.3 Idempotency-Key Format: UUIDv7 (RFC 9562)

The Iceberg REST spec requires the Idempotency-Key header to be a UUIDv7 in string form, as defined by RFC 9562. RFC 9562 obsoletes RFC 4122 and standardizes the newer time-ordered UUID versions (6, 7, and 8). The requirement is stated directly in the spec's Idempotency-Key parameter definition: "Key format: UUIDv7 in string form (RFC 9562)" (see rest-catalog-open-api.yaml).

UUIDv7 encodes a 48-bit Unix timestamp (milliseconds) in its most-significant bits, followed by version/variant bits and random data. This gives it two properties this design benefits from:

  • Time-ordered / monotonic: Keys generated later sort after keys generated earlier. Used as a primary key, inserts are append-mostly, which reduces B-tree page splits and index fragmentation on MySQL/PostgreSQL compared to fully-random UUIDv4.
  • Embedded creation time: The timestamp prefix lets the server derive an approximate creation instant from the key itself, useful for diagnostics and as a sanity check, and aligns naturally with TTL-based expiry.

Why this design follows RFC 9562:

  1. Spec compliance: The Iceberg REST spec mandates UUIDv7 in string form (RFC 9562). Validating against RFC 9562 (version nibble 7, correct variant bits, 36-char canonical form) lets the server reject malformed keys with 400 Bad Request before touching storage, and guarantees interoperability with any spec-compliant client.
  2. Storage efficiency: The time-ordered property keeps the idempotency_key primary-key index compact and insert-friendly, which matters most for the jdbc store under high write throughput.
  3. No custom format: Following the standard means the server does not impose a non-standard key format that clients would have to special-case.

Validation rules applied by the server:

  • Length must be exactly 36 characters (canonical hyphenated form), matching the spec's minLength/maxLength of 36.
  • Must parse as a UUID whose version field reports 7.
  • Must use the RFC 9562 variant (the two most-significant bits of the variant octet are 10).

Correctness does not depend on the embedded timestamp: expiry uses a server-assigned expires_at (see Section 4). The timestamp is used only as a defense-in-depth sanity check and for diagnostics.


2. Goals

  1. Prevent duplicate side-effects when clients retry mutations with the same key.
  2. Work correctly in multi-node deployments (shared storage).
  3. Survive node failures (durable state).
  4. Minimal latency overhead on the happy path (single extra DB round-trip).
  5. Configurable storage backend (pluggable SPI).
  6. Spec-compliant: validate UUIDv7 format, advertise lifetime in config.

Non-Goals

  • Cross-datacenter replication of idempotency records.
  • Idempotency for read (GET/HEAD) operations.
  • Guaranteed delivery (client-side concern).
  • Heartbeat/liveness tracking. Deployments must bound mutation duration and clock skew below the configured reuse window; see Section 5.4.

3. Architecture

3.1 Request Flow Overview

Client                 Load Balancer            Node A / Node B
  |                         |                         |
  |-- POST + Idempotency-Key: <uuid> --------------->|
  |                         |                         |
  |                         |          +--------------+---------------+
  |                         |          | 1. Validate UUIDv7 format    |
  |                         |          | 2. store.reserve(key)        |
  |                         |          |    +- Claim -> execute       |
  |                         |          |    +- Empty -> replay        |
  |                         |          | 3. Execute mutation          |
  |                         |          | 4. store.finalize(key, resp) |
  |                         |          +--------------+---------------+
  |<-- Response ------------------------------------ |

3.2 IdempotencyStore SPI

A storage-agnostic interface that any backend can implement:

public interface IdempotencyStore extends Closeable {

  /**
   * Attempt to reserve a key. Returns empty if already reserved or finalized.
   *
   * @param idempotencyKey the client-provided UUIDv7 key
   * @param operationBinding request identity, e.g. "POST /v1/cat1/namespaces/ns1/tables"
   * @param expiresAtMs deadline in Unix epoch milliseconds
   * @return true if acquired, false if the key is live
   */
  boolean reserve(String idempotencyKey, String operationBinding, long expiresAtMs);

  /**
   * Load a finalized record for replay.
   *
   * @param idempotencyKey the client-provided key
   * @return the record if finalized, empty if not yet finalized or not found
   */
  Optional<IdempotencyRecord> load(String idempotencyKey);

  /**
   * Mark a reserved key as finalized with the response to replay on duplicates.
   *
   * @param idempotencyKey the client-provided key
   * @param httpStatus the HTTP status code of the original response
   * @param responseSummary serialized response body (JSON string)
   */
  void finalizeRecord(String idempotencyKey, int httpStatus, String responseSummary);

  /**
   * Release a reservation so the client can retry with the same key.
   * Called when the mutation fails with a retryable error.
   *
   * @param idempotencyKey the client-provided key
   */
  void release(String idempotencyKey);

  /**
   * Purge expired records. Called periodically by a background task.
   *
   * @param beforeMs inclusive expiry cutoff in Unix epoch milliseconds
   * @return number of records purged
   */
  int purgeExpired(long beforeMs);
}

3.3 IdempotencyRecord

public class IdempotencyRecord {
  private final String idempotencyKey;     // UUIDv7 (RFC 9562), 36-char canonical form
  private final String operationBinding;   // e.g., "POST /v1/cat1/namespaces/ns1/tables"
  private final Integer httpStatus;        // null while reserved / in-progress
  private final String responseSummary;    // serialized response body (JSON)
  private final long createdAtMs;          // unix epoch millis (matches BIGINT column)
  private final long expiresAtMs;          // unix epoch millis (matches BIGINT column)
}

Timestamps are stored as long unix epoch milliseconds to match Gravitino's existing metadata tables (e.g., the deleted_at / timestamp columns in metalake_meta, catalog_meta, and commit_metrics_report), which all use BIGINT epoch millis rather than SQL TIMESTAMP.

3.4 Storage Implementations

Implementation Use Case Durability Multi-Node
InMemoryIdempotencyStore Dev, testing, single No No
JdbcIdempotencyStore Production Yes Yes

The JDBC implementation leverages Gravitino's existing relational backend (H2 for dev, MySQL or PostgreSQL for production).

3.5 In-Memory Store Capacity and Eviction

The InMemoryIdempotencyStore is a node-local Caffeine cache bounded by two limits:

  • Time-based: Caffeine.expireAfterWrite(lifetime) removes records once their reuse window has elapsed (same TTL as expires_at).
  • Size-based: Caffeine.maximumSize(idempotency-max-entries) caps the number of retained records.

When the number of stored keys exceeds idempotency-max-entries, Caffeine evicts entries using its Window-TinyLFU policy (approximate LRU) before they naturally expire. The consequences are:

  • An evicted-but-not-yet-expired key loses its stored response. A subsequent retry with that key is then treated as a new request and the mutation is re-executed. This weakens the idempotency guarantee under memory pressure.
  • Because eviction can also drop an in-progress RESERVED entry, the in-memory store is explicitly documented as best-effort, single-node, dev/test only. Production deployments MUST use the jdbc store, which has no such cap.

Mitigations:

  • Size idempotency-max-entries for the expected peak throughput multiplied by the key lifetime (roughly requests_per_second * lifetime_seconds).
  • Emit an eviction-rate metric and log a warning when eviction is frequent, signaling the cache is under-provisioned or that the jdbc store should be used instead.

4. Database Schema

The table name, column names, and column types follow Gravitino's existing metadata table conventions (see scripts/mysql/schema-*.sql and scripts/mysql/iceberg-metrics-schema-*.sql): a *_meta table name, backtick-quoted snake_case columns, BIGINT unix-epoch-millis timestamps, a MEDIUMTEXT audit_info column, per-column COMMENTs, and ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin.

MySQL:

CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (
  `idempotency_key`  VARCHAR(36)         NOT NULL     COMMENT 'client-provided UUIDv7 idempotency key',
  `http_method`      VARCHAR(16)         NOT NULL     COMMENT 'HTTP method of the request',
  `request_uri`      MEDIUMTEXT          NOT NULL     COMMENT 'encoded request path and sorted query string',
  `http_status`      INT(10) UNSIGNED    DEFAULT NULL COMMENT 'HTTP status of finalized response, NULL while reserved',
  `response_summary` MEDIUMTEXT          DEFAULT NULL COMMENT 'serialized response body (JSON) for replay',
  `audit_info`       MEDIUMTEXT          NOT NULL     COMMENT 'idempotency record audit info',
  `created_at`       BIGINT(20) UNSIGNED NOT NULL     COMMENT 'record created at (unix epoch millis)',
  `expires_at`       BIGINT(20) UNSIGNED NOT NULL     COMMENT 'record expires at (unix epoch millis)',
  PRIMARY KEY (`idempotency_key`),
  KEY `idx_iim_expires` (`expires_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Iceberg REST idempotency records';

The H2 and PostgreSQL variants use the same columns. All three backends ship the table in scripts/<backend>/schema-2.0.0-<backend>.sql and scripts/<backend>/upgrade-1.3.0-to-2.0.0-<backend>.sql.

Hard-deleted, released, or purged keys are treated as never seen. That matches common HTTP Idempotency-Key stores and the Iceberg REST reuse window (clients SHOULD NOT reuse a key after expiry). Size the reuse window so mutations finish before expiry.

The HTTP method is stored in http_method. The request_uri column stores the encoded path plus the sorted, encoded query string when present. MySQL uses MEDIUMTEXT because the default HTTP request limit permits targets longer than MySQL's 64 KiB TEXT limit.

4.1 Row Lifecycle

  1. RESERVED: Row inserted with http_status = NULL. Mutation is executing.
  2. FINALIZED: http_status and response_summary written. Ready for replay.
  3. EXPIRED: expires_at <= now(). Eligible for reclaim or background cleanup (see Section 5.4).

4.2 Conflict Handling

reserve() attempts a plain INSERT. After a duplicate-key rollback, a separate transaction replaces the matching row only if it is expired. If no expired row matches, the store retries once with a fresh expiry cutoff in case purge or release freed the key. If neither attempt claims the key, it returns empty. Other SQL errors propagate. Only finalized, unexpired records can be loaded for replay.


5. Detailed Request Flow

5.1 Happy Path (First Request)

  1. If idempotency is disabled (idempotency-enabled=false, the default), ignore the Idempotency-Key header and execute the mutation directly.
  2. Extract Idempotency-Key header; validate UUIDv7 format (400 if invalid).
  3. If header absent, execute mutation directly (no idempotency overhead).
  4. Call store.reserve(key, binding, now + lifetime) to acquire the key.
  5. If reserve returns true, execute the mutation and call store.finalizeRecord(key, status, body).
  6. Return response to client.

5.2 Replay Path (Duplicate Key)

  1. Extract and validate header.
  2. Call store.reserve(key, binding, expiresAt). An empty result indicates a duplicate.
  3. Call store.load(key):
    • If finalized: reconstruct and return cached response.
    • If in-progress (not yet finalized): return 409 Conflict with Retry-After header (the mutation may still be executing, or its response was not retained).
  4. Return cached response.

5.3 Execution Failure

The manager distinguishes failures before execution, mutation outcomes, and response-persistence failures:

  • Reservation or replay lookup failure: return 503 Service Unavailable with Retry-After without executing the mutation. Do not release a reservation whose commit acknowledgement may have been lost. Retry with the same key within its reuse window; reconcile catalog state before retrying outside it.
  • Retryable mutation errors (5xx, authentication/authorization outcomes, or a thrown action exception): call store.release(key) so the client can retry with the same key. A mutation failure can still have an uncertain catalog outcome; a 5xx is not proof that the catalog was unchanged.
  • Terminal errors (e.g., AlreadyExistsException): call store.finalizeRecord(key, 409, errorBody) so retries get the same error response.
  • Terminal response cannot be retained (serialization, write, read-back failure, or a no-op finalize): return the original mutation response and leave any existing reservation until expiry. This prevents immediate re-execution; a retry receives an in-flight 409 while the unfinalized reservation remains.

This matches the Iceberg REST spec's finalization rules for the Idempotency-Key header:

  • Finalize & replay: 200, 201, 204, and deterministic terminal 4xx responses (including 409 such as AlreadyExists, NamespaceNotEmpty).
  • Do not finalize (not stored/replayed): 5xx responses, which are treated as retryable and cause release().

5.4 Expiry and Cleanup of Outdated Data

Every record carries expires_at = created_at + idempotency-key-lifetime. The spec states catalogs SHOULD NOT expire keys before the advertised lifetime, so cleanup only ever removes records whose window has already elapsed.

There is no heartbeat or in-flight renewal. The configured lifetime must exceed the maximum reservation-to-response-persistence duration, maximum replica clock skew, and a safety margin. This bound includes lock waits, backend retries, and JVM pauses; an HTTP timeout alone does not stop a catalog mutation. If those bounds cannot be enforced, expiry can allow overlapping execution, so callers must not rely on an at-most-once guarantee or blindly retry after the window.

JDBC store. Each store owns a background task scheduled every idempotency-cleanup-interval that calls store.purgeExpired(now). Use one store per service instance and close it at service shutdown. MySQL and H2 use:

DELETE FROM iceberg_idempotency_meta WHERE expires_at <= ? LIMIT ?;
  • Deletes are performed in at most 100 batches of 1,000 rows per pass to avoid long-held locks and large transactions. Larger backlogs wait for later passes; expiry is enforced on access independently of cleanup.
  • The idx_iim_expires index makes the predicate efficient.
  • PostgreSQL selects a bounded set of candidate keys in a subquery and rechecks expiry on the target row. MySQL and H2 recheck the target-row predicate after a lock wait, preserving reservations concurrently reclaimed with a future deadline.
  • Concurrent cleanup does not require leader election. Replicas must synchronize system clocks: there is no clock-skew grace period, and a fast replica can reclaim or purge a key another replica still considers live. Monitor clock offset and synchronization health as a replay-safety requirement.

In-memory store. No separate task is needed: Caffeine's expireAfterWrite(lifetime) removes expired entries lazily/automatically, and size-based eviction bounds memory (see Section 3.5).


6. Configuration

All keys use the gravitino.iceberg-rest. prefix used by the Iceberg REST server. Only idempotency-key-lifetime is defined by the Iceberg REST spec and advertised to clients; every other key is Gravitino server-side configuration and is not exposed via GET /v1/config.

Config Key Default Description
gravitino.iceberg-rest.idempotency-enabled false Master switch. Disabled by default (matching Polaris). When false, the Idempotency-Key header is ignored and no lifetime is advertised.
gravitino.iceberg-rest.idempotency-key-lifetime PT30M Client reuse window (ISO-8601 duration). Advertised to clients as the spec-defined idempotency-key-lifetime in GET /v1/config.
gravitino.iceberg-rest.idempotency-store-type in-memory in-memory or jdbc.
gravitino.iceberg-rest.idempotency-max-entries 10000 Max cached entries (in-memory store only). See Section 3.5.
gravitino.iceberg-rest.idempotency-cleanup-interval PT5M Interval for the background task that purges expired records (jdbc store).

6.1 Iceberg Spec Configuration

The only idempotency setting defined by the Iceberg REST spec is idempotency-key-lifetime, together with the Idempotency-Key request header. Both are defined in the Iceberg REST OpenAPI spec:

When idempotency is enabled, it is advertised in GET /v1/config as:

{
  "defaults": {
    "idempotency-key-lifetime": "PT30M"
  }
}

Per the spec, presence of this field signals that the server supports Idempotency-Key semantics; when absent (i.e., idempotency-enabled=false), clients MUST assume idempotency is not supported.

6.2 Database Configuration (jdbc store)

When idempotency-store-type=jdbc, the store reuses the initialized Gravitino relational entity store's connection pool in auxiliary mode. It supports H2, MySQL, and PostgreSQL and has no separate idempotency-jdbc-* connection settings. Multiple replicas must connect to the same shared MySQL or PostgreSQL database. The store does not own or close the shared pool.

Standalone Iceberg REST servers cannot use this backend. The Iceberg REST server JAR contains the store interface, factory, and both built-in implementations. The factory resolves the in-memory and jdbc aliases to those implementations. The configuration keys live in iceberg-common. Apply the schema or upgrade scripts before enabling the store. See the JDBC operations guidance for clock synchronization, cleanup limits, and deployment requirements.


7. Comparison with Polaris

Aspect Polaris (PR #3205) This Design
Storage Postgres-specific Gravitino relational backend (H2/MySQL/PG)
Heartbeat Yes (long-running ops) No; requires bounded mutation duration and clock skew
Reconciliation Yes (crash recovery) TTL-based expiry; retain reservations on response-storage failure
Executor ownership Yes (multi-worker) No (single-owner per key via DB constraint)
Response storage Minimal summary + pointer Full response body (mutation responses are small)

This design uses a fixed reuse window rather than heartbeat-based ownership. It therefore requires the duration and clock-skew bounds in Section 5.4 and cannot guarantee at-most-once execution for unbounded mutations. Supporting those operations safely would require a separate lease-renewal and catalog-side design; the idempotency record alone cannot stop an already running catalog mutation.


8. Implementation Phases

Phase 1: SPI and In-Memory Store

  • Define the IdempotencyStore interface and IdempotencyRecord.
  • Implement InMemoryIdempotencyStore using Caffeine cache.
  • Wire into endpoint operations with @HeaderParam("Idempotency-Key").
  • Advertise idempotency-key-lifetime in GET /v1/config.
  • Unit tests for all mutation endpoints.

Phase 2: JDBC Store

  • Add iceberg_idempotency_meta table schema for H2, MySQL, and PostgreSQL.
  • Implement JdbcIdempotencyStore using Gravitino's existing connection pool.
  • Package the store interface, implementations, and factory in iceberg/iceberg-rest-server.
  • Background cleanup task for expired records.
  • Integration tests with testcontainers.

Phase 3: Observability (Out of Scope for Now)

Deferred until the SPI and JDBC store land; not required for the initial implementation:

  • Metrics: cache hit rate, replay count, store latency, in-memory eviction rate.

9. Testing Strategy

  • Unit tests: Store SPI implementations (in-memory and JDBC), UUIDv7 / RFC 9562 validation (reject UUIDv4, wrong length, bad variant), replay logic, terminal vs. retryable error handling, in-memory size-based eviction, and purgeExpired batching.
  • Integration tests: Multi-threaded concurrent reserve/finalize on the same key, TTL-based expiry, cleanup task removing only expired rows, JDBC store with H2.
  • E2E tests: With idempotency-enabled=false the header is ignored; with it enabled, retry with same key returns cached response, different key executes fresh, invalid key returns 400, and idempotency-key-lifetime is advertised in GET /v1/config.