World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
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:
- Execute the mutation on first receipt and store the response.
- Return the stored response on subsequent retries with the same key.
- Advertise the key reuse window via
idempotency-key-lifetimeinGET /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:
- Spec compliance: The Iceberg REST spec mandates
UUIDv7 in string form (RFC 9562). Validating against RFC 9562 (version nibble7, correct variant bits, 36-char canonical form) lets the server reject malformed keys with400 Bad Requestbefore touching storage, and guarantees interoperability with any spec-compliant client. - Storage efficiency: The time-ordered property keeps the
idempotency_keyprimary-key index compact and insert-friendly, which matters most for thejdbcstore under high write throughput. - 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/maxLengthof 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
- Prevent duplicate side-effects when clients retry mutations with the same key.
- Work correctly in multi-node deployments (shared storage).
- Survive node failures (durable state).
- Minimal latency overhead on the happy path (single extra DB round-trip).
- Configurable storage backend (pluggable SPI).
- 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 asexpires_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
RESERVEDentry, the in-memory store is explicitly documented as best-effort, single-node, dev/test only. Production deployments MUST use thejdbcstore, which has no such cap.
Mitigations:
- Size
idempotency-max-entriesfor the expected peak throughput multiplied by the key lifetime (roughlyrequests_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
jdbcstore 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
- RESERVED: Row inserted with
http_status = NULL. Mutation is executing. - FINALIZED:
http_statusandresponse_summarywritten. Ready for replay. - 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)
- If idempotency is disabled (
idempotency-enabled=false, the default), ignore theIdempotency-Keyheader and execute the mutation directly. - Extract
Idempotency-Keyheader; validate UUIDv7 format (400 if invalid). - If header absent, execute mutation directly (no idempotency overhead).
- Call
store.reserve(key, binding, now + lifetime)to acquire the key. - If reserve returns true, execute the mutation and call
store.finalizeRecord(key, status, body). - Return response to client.
5.2 Replay Path (Duplicate Key)
- Extract and validate header.
- Call
store.reserve(key, binding, expiresAt). An empty result indicates a duplicate. - Call
store.load(key):- If finalized: reconstruct and return cached response.
- If in-progress (not yet finalized): return
409 ConflictwithRetry-Afterheader (the mutation may still be executing, or its response was not retained).
- 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 UnavailablewithRetry-Afterwithout 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): callstore.release(key)so the client can retry with the same key. A mutation failure can still have an uncertain catalog outcome; a5xxis not proof that the catalog was unchanged. - Terminal errors (e.g.,
AlreadyExistsException): callstore.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
409while 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 terminal4xxresponses (including409such asAlreadyExists,NamespaceNotEmpty). - Do not finalize (not stored/replayed):
5xxresponses, which are treated as retryable and causerelease().
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_expiresindex 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:
Idempotency-Keyparameter andidempotency-key-lifetimeCatalogConfigfield:open-api/rest-catalog-open-api.yaml
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
IdempotencyStoreinterface andIdempotencyRecord. - Implement
InMemoryIdempotencyStoreusing Caffeine cache. - Wire into endpoint operations with
@HeaderParam("Idempotency-Key"). - Advertise
idempotency-key-lifetimeinGET /v1/config. - Unit tests for all mutation endpoints.
Phase 2: JDBC Store
- Add
iceberg_idempotency_metatable schema for H2, MySQL, and PostgreSQL. - Implement
JdbcIdempotencyStoreusing 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
purgeExpiredbatching. - 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=falsethe header is ignored; with it enabled, retry with same key returns cached response, different key executes fresh, invalid key returns 400, andidempotency-key-lifetimeis advertised inGET /v1/config.