Architecting a Multi-Tenant Cloud SQL Platform on Apache Iceberg

Hard · System Design · Software Engineer · Onsite

Prompt

Architect a cloud-hosted SQL execution service backed by Apache Iceberg tables on object storage. Analysts running ad-hoc queries in a browser workspace and automated pipelines calling an HTTP API both submit SQL statements through your platform, which plans and executes each statement against Iceberg tables and delivers the resulting rows or mutation status.

Your design should clarify what classes of SQL statements (SELECT queries alone versus INSERT, UPDATE, DELETE, and MERGE mutations) and workload profiles (sub-second interactive exploration versus long-running batch jobs and large exports) the platform supports, how multiple tenant organizations share or isolate compute and table access, whether to build a query engine from scratch or orchestrate an existing distributed engine, and how your service coordinates alongside external streaming or batch pipelines committing to the same Iceberg catalog.

Scope & Expectations

  • Establish concrete scale assumptions (concurrency, largest table footprint, result payload sizes, latency SLOs) and justify wrapping versus building the distributed SQL engine.
  • Design an asynchronous-capable statement API and result-delivery pipeline that handles both sub-second UI queries and multi-minute executions returning multi-gigabyte exports.
  • Detail how Iceberg snapshots, manifest lists, and file-level statistics prune partitions and files prior to reading object storage, and how concurrent writers commit atomically through the catalog.
  • Cover multi-tenant admission fairness, scoped storage authorization, crash recovery, and automated background maintenance to keep tables healthy over time.

Step-by-step walkthrough

  1. Clarify requirements, core concepts, and assumptions

    Three building blocks define the physics of this system—let's state each in one plain sentence before gathering requirements:

    • Object storage (such as Amazon S3 or GCS): cheap, infinitely scalable cloud storage where files cannot be edited in place and each read request carries ~50–150 ms of network latency.
    • Apache Parquet: a columnar file format that stores each column's values contiguously alongside min/max statistics, allowing a query that touches 4 out of 100 columns to skip 96% of the bytes on disk.
    • Apache Iceberg: an open table format that organizes immutable Parquet files in object storage into a full ACID SQL table using a tree of immutable metadata files and one atomic pointer stored in a catalog.

    With those constraints in mind, let's pin down six architectural assumptions:

    1. Read-only vs. writes too? Both. SELECT accounts for ~95% of traffic, while ~5% runs INSERT, UPDATE, DELETE, MERGE, and CREATE TABLE AS SELECT (CTAS).
    2. Interactive vs. batch? Both. Interactive analysts and dashboards expect p50 <= 2 s and p95 <= 15 s (for queries scanning <= 50 GB after pruning) with fast first-row display. Scheduled batch transformations and large exports run from minutes to hours and must never starve interactive queries.
    3. Multi-tenancy and isolation? Yes: ~300 tenant organizations and ~5,000 active users. Tenants require strict data isolation (zero cross-tenant visibility) and load isolation (one tenant's 2-hour MERGE cannot slow another tenant's dashboard).
    4. Build a SQL engine vs. wrap an existing one? Wrap proven distributed engines with native Iceberg connectors—Trino for low-latency interactive queries, and Trino Fault-Tolerant Execution (or Spark) for multi-hour batch jobs and table maintenance. Writing a distributed SQL optimizer from scratch takes years; our service owns the statement lifecycle, admission control, multi-tenant security, result delivery, and automated Iceberg maintenance.
    5. Scale targets? 1.5M statements/day, 600 concurrently executing statements at peak (2,000 including queued). Tables range from a 50 GB median up to a 200 TB largest table (2,000,000 Parquet files across 2 years = 730 daily partitions). Results range from a few kilobytes in the web UI (capped at 10,000 preview rows) up to 100 GB exported via API.
    6. Catalog and external writers? An Iceberg REST Catalog stores the authoritative pointer to each table's current metadata file. External streaming jobs (appending every minute) and customer Spark jobs also commit to the same catalog, so our service cannot rely on private in-memory locks to coordinate writes.

    Functional & non-functional summary

    • Submit, monitor progress, paginate/download results (retained 24 hours), cancel statements, and query historical snapshots (time travel).
    • Snapshot isolation for reads, atomic single-table commits for writes, 99.9% API availability, surviving client disconnects and service restarts, per-tenant scan/concurrency quotas, and full audit logging.
  2. Back-of-the-envelope sizing

    Sizing a query on the 200 TB table reveals why metadata-driven pruning separates an unusable system from a sub-second UI:

    Workload & cluster throughput
      Daily volume:                1.5M statements/day -> ~17.4/s average, ~100/s peak submissions
      Largest table:               200 TB Parquet across 2,000,000 files (~100 MB avg), 730 days
      Per-worker scan speed:       ~1 GB/s compressed Parquet (25 Gbps NIC, CPU decompression bound)
    
    Why pruning decides everything (100 workers = 100 GB/s aggregate scan speed)
      1. Naive full table scan:    200,000 GB / 100 GB/s = 2,000 s (~33.3 minutes!)
      2. Prune to 1 day (1/730):   ~274 GB across ~2,740 files -> 2.74 s
      3. Read 5 of 100 columns:    ~5% of bytes = ~13.7 GB -> ~0.14 s of raw data I/O!
    
    Metadata planning cost (once data I/O shrinks to 0.14 s, metadata latency dominates!)
      Manifest entry size:         ~1–3 KB uncompressed per data file (column min/max/null counts)
      2,000,000 files:             ~2–6 GB uncompressed across ~400–600 compressed Avro manifests (~8 MB each)
      Cold S3 chain:               Catalog -> metadata.json -> manifest list -> manifests -> Parquet footer
                                   = 4 sequential S3 round trips x ~100 ms = ~400 ms before reading 1 row!
      Warm SSD/RAM metadata cache: 1 lightweight catalog check + local manifest filter = ~20–40 ms
    
    Fleet & storage sizing
      Data scanned across platform: 1.5M queries x 2 GB mean after pruning = 3 PB/day (~35 GB/s avg)
                                    -> ~35 workers sustained avg; ~160–200 workers across pools for 4x peak + headroom
      Result store (24h TTL):       1.5M queries x 1 MB mean result = ~1.5 TB active object storage
      Catalog read/commit QPS:      ~50 table loads/s avg (~300/s peak); ~3–5 streaming/DML commits/s
    
  3. API design: statements as asynchronous resources

    Because SQL execution frequently outlasts a single HTTP connection—cloud load balancers drop idle sockets at ~60 seconds, browser tabs close, and a 100 GB export cannot fit inside one JSON payload—we model every submission as a durable Statement resource, adding an optional short wait_timeout_s (0..10 seconds) so fast interactive queries still return in one network round trip:

    POST /v1/statements
      Request:
        {
          "sql": "SELECT region, SUM(amount) FROM sales.orders WHERE ...",
          "catalog": "prod",
          "namespace": "sales",
          "mode": "interactive" | "batch",
          "wait_timeout_s": 5,
          "result_format": "arrow" | "json" | "parquet" | "csv",
          "idempotency_key": "client-uuid-9182"
        }
      Responses:
        200 OK       (finished within 5 s):
          {"statement_id": "stmt_01J...", "state": "SUCCEEDED",
           "tables_read": [{"table": "sales.orders", "snapshot_id": 8841209}],
           "result": {"columns": [...], "rows": [...first page...], "next_page_token": "..."}}
        202 Accepted (still running at 5 s):
          {"statement_id": "stmt_01J...", "state": "RUNNING",
           "progress": {"splits_done": 14, "splits_total": 120, "bytes_scanned": 1820000000}}
    
    GET  /v1/statements/{id}                 -> current state, progress, snapshot IDs read/committed, or error
    GET  /v1/statements/{id}/events          -> Server-Sent Events (SSE) stream for live UI progress bars
    GET  /v1/statements/{id}/result?page=... -> inline JSON rows (<= 10 MB) OR list of presigned S3 chunk URLs
    POST /v1/statements/{id}:cancel          -> idempotent cancellation request
    GET  /v1/statements?user=&state=&since=  -> paginated query history
    

    Key API design choices: - idempotency_key: a unique client token cached per tenant for 24 hours so retrying a timed-out POST never executes INSERT or MERGE twice. - Immutable result pages: once SUCCEEDED, result chunks sit frozen in object storage for 24 hours, so re-fetching page 3 or resuming an interrupted 100 GB download always returns identical bytes. - Time-travel SQL: users query historical state via standard SQL (SELECT * FROM orders FOR VERSION AS OF 8841200 or FOR TIMESTAMP AS OF TIMESTAMP '2026-11-01 00:00:00 UTC'), and every GET /v1/statements/{id} response echoes the exact snapshot_id read so results are reproducible.

  4. Data model: Iceberg's immutable tree and the service database

    Think of an Iceberg table like a library card catalog pointing to immutable books on object storage shelves. Nothing below the top catalog pointer is ever modified in place:

      [ Iceberg REST Catalog ]
         (namespace, table) ---> s3://.../metadata/v0042.metadata.json   <-- ONLY mutable pointer (CAS)
                                        |
                                        v
      [ metadata.json ]          Schemas, partition specs, sort orders, snapshot history,
                                 current_snapshot_id = S42
                                        |
                                        v
      [ Manifest List (Avro) ]   1 entry per manifest file for Snapshot S42:
                                 manifest path, content (DATA | DELETES),
                                 partition min/max range (e.g., order_day in [2026-11-01, 2026-11-05])
                                    /                       \
                                   v                         v
      [ Data Manifests (Avro) ]                        [ Delete Manifests (Avro) ]
        1 entry per Parquet data file:                   1 entry per delete file:
        status (ADDED | EXISTING | DELETED),             position deletes (file_path, row_pos),
        partition tuple, record_count, file_size,        equality deletes (key values), or
        per-column [lower_bound, upper_bound], nulls     v3 deletion vectors (Puffin bitmaps)
                    |
                    v
      [ Parquet Data Files ]     Row groups -> Column chunks -> Pages (with footer stats & bloom filters)
    

    Alongside Iceberg, our service maintains a lightweight relational database (PostgreSQL) for statement state, multi-tenant governance, and table health:

    statements (
      statement_id PK, tenant_id, user_id, idempotency_key,
      sql_text, normalized_sql_hash, mode, state,
      owner_instance, lease_expires_at,            -- crash recovery across service replicas
      engine_cluster_id, engine_query_id,
      tables_read JSONB, committed_snapshot JSONB, -- [{table, snapshot_id, schema_id}]
      est_scan_bytes, actual_scan_bytes, cpu_ms,
      result_prefix, result_rows, result_bytes, result_expires_at,
      error_code, error_message, submitted_at, finished_at, cancel_requested_at
    )
    
    tenants (
      tenant_id PK, tier, fair_share_weight, dedicated_cluster_id,
      max_running_interactive, max_running_batch, max_queued, max_scan_bytes_per_query
    )
    
    table_health (
      table_fqn PK, current_snapshot_id, data_file_count, avg_file_size_mb,
      delete_file_count, manifest_count, last_compacted_at, last_expired_at
    )
    

    Statement lifecycle state machine:

      QUEUED --> PLANNING --> RUNNING --> FINISHING --> SUCCEEDED --(after 24h)--> EXPIRED
        |           |            |            |
        +-----------+------------+------------+-------> CANCELED | FAILED
    

    FINISHING guarantees a statement is never marked SUCCEEDED until all result chunks are flushed to object storage (for reads) or the catalog pointer swap has succeeded (for writes).

  5. High-level architecture

        Web UI         REST / SDK Clients       BI Tools (JDBC/ODBC Proxy)
           \                   |                         /
            +-----------[ API Gateway ]-----------------+   (SSO AuthN, TLS, rate limits)
                               |
                    [ Statement Service ] <===========> [ PostgreSQL Statement DB ]
                     - Parse & authorize                  (leases, history, quotas,
                     - Plan & estimate scan bytes          result cache index, health)
                     - Manage leases & retries
                               |
                    [ Admission Controller ]
                     - Per-tenant + per-user fair queues
                     - Route by mode & estimated bytes
                  /                    |                     \
                 v                     v                      v
      +---------------------+  +--------------------+  +---------------------+
      | Interactive Pools   |  | Batch Pool         |  | Maintenance Pool    |
      | (Trino clusters +   |  | (Fault-tolerant    |  | (Compaction, orphan |
      |  local NVMe SSD     |  |  Trino / Spark,    |  |  cleanup, manifest  |
      |  manifest & Parquet |  |  task retries,     |  |  rewrites, snapshot |
      |  caches)            |  |  S3 shuffle spill) |  |  expiration)        |
      +----------+----------+  +---------+----------+  +----------+----------+
                 \                       |                       /
                  +----------------------+----------------------+
                                         |
                                         v
                         [ Iceberg REST Catalog ]
                           - Atomic compare-and-swap on metadata.json pointer
                           - Vends short-lived, table-scoped S3 credentials
                                         |
                                         v
           +-------------------------------------------------------------+
           | Object Storage                                              |
           |  1. Warehouse Bucket: metadata, manifests, Parquet/deletes  |
           |  2. Result Bucket (24h lifecycle): /results/<tenant>/<id>/  |
           +-------------------------------------------------------------+
    

    Read path in 4 beats: Client POSTs SQL -> Statement Service authorizes tables and asks the coordinator to plan from Iceberg metadata -> Admission Controller checks estimated scan bytes against tenant quota and dispatches splits to an Interactive Pool -> Workers read pruned Parquet columns and write Arrow/Parquet chunks straight to the Result Bucket while the service updates status to SUCCEEDED.

  6. Deep dive 1: multi-level metadata pruning prior to scanning Parquet

    Consider an analyst running this query against our 200 TB, 2,000,000-file orders table partitioned by day(order_ts):

    SELECT region, SUM(amount)
    FROM sales.orders
    WHERE order_ts >= TIMESTAMP '2026-11-01 00:00:00 UTC'
      AND order_ts <  TIMESTAMP '2026-11-02 00:00:00 UTC'
      AND status = 'REFUNDED'
    GROUP BY region;
    

    Notice the user filtered on raw order_ts, not a separate order_day column. Iceberg supports hidden partitioning—storing the day(order_ts) transform rule in metadata so the query planner automatically converts timestamp filters into partition filters without exposing extra partition columns to users.

    The 6-stage pruning funnel (zero data files opened during stages 1–4):

    1. Catalog -> Snapshot: 1 catalog RPC returns metadata.json; the planner pins current_snapshot_id.
    2. Manifest List -> Manifests: Each manifest entry in the manifest list stores [min_day, max_day]. Out of 500 manifests spanning 730 days, ~498 have day ranges outside 2026-11-01 and are skipped without even opening those manifest files.
    3. Manifests -> Live Data Files: Inside the ~2 surviving manifests, the planner skips any entry with status == 'DELETED' (tombstones left behind by earlier compactions so snapshot diffs remain traceable), keeps entries where partition.day == '2026-11-01' (~2,740 files), and checks per-file column [lower_bound, upper_bound] on status: any file whose status bounds are ['CANCELED', 'PAID'] cannot contain 'REFUNDED' and is skipped!
    4. Delete-file matching: Only delete manifests overlapping 2026-11-01 with a sequence number >= the surviving data files' sequence numbers are scheduled.
    5. Columnar & row-group pruning inside workers: Workers fetch only the Parquet footer and the 3 needed column chunks (order_ts, status, region, amount), skipping row groups via Parquet page indexes and Bloom filters.
    6. Dynamic join filtering (at runtime): When joining a small filtered customers dimension to orders, workers broadcast matching customer_id min/max/Bloom filters back to the orders scan to skip partitions and files mid-query.
    def plan_candidate_files(snapshot, target_day: str, read_manifest_cached, may_contain_status) -> list:
        """Prune 2,000,000 Iceberg files down to matching candidates using metadata only."""
        surviving_data_files = []
    
        for manifest_ref in snapshot.manifest_list:
            # Stage 1: Only inspect DATA manifests (DELETES manifests are matched separately).
            if manifest_ref.content != "DATA":
                continue
    
            # Stage 2: Manifest-list partition summary check skips whole Avro manifest files.
            if manifest_ref.max_day < target_day or manifest_ref.min_day > target_day:
                continue
    
            # Stage 3: Read manifest (from local SSD/RAM cache; manifest paths are immutable!).
            for entry in read_manifest_cached(manifest_ref.path):
                # Skip DELETED tombstones recorded when older snapshots compacted/removed files.
                if entry.status == "DELETED":
                    continue
                if entry.partition_day != target_day:
                    continue
    
                # Stage 4: File-level column min/max bounds skip files missing status='REFUNDED'.
                if not may_contain_status(entry.lower_bounds, entry.upper_bounds, "REFUNDED"):
                    continue
    
                surviving_data_files.append(entry.data_file)
    
        return surviving_data_files
    

    Answering queries purely from metadata (zero Parquet I/O): SELECT COUNT(*) FROM sales.orders WHERE order_ts >= DATE '2026-11-01' can sum entry.record_count directly from manifests in milliseconds—provided the predicate aligns cleanly with partition boundaries (or every surviving file's min/max bounds fall completely inside the filter with zero nulls) and zero delete files apply to those partitions. Numeric/date MIN and MAX work under the same rule when full column bounds exist; string MIN/MAX generally cannot because Iceberg truncates string bounds to 16 characters by default (truncate(16)) to keep manifests small.

    Keeping planning fast at scale: Because manifest lists and manifests are 100% immutable once written, coordinators cache them in RAM and local NVMe SSDs keyed simply by file path—zero cache invalidation logic is ever required! And because planning runs before worker execution, it yields an accurate est_scan_bytes figure so our Admission Controller can block an accidental 200 TB scan (400 Scan limit exceeded) before spending a cent of worker compute.

  7. Deep dive 2: durable statement execution and chunked result delivery

    Lease-based ownership across stateless service replicas

    When Instance A dispatches stmt_01J to Trino cluster interactive-2, it stamps owner_instance = 'inst-A' and lease_expires_at = now() + 30s in PostgreSQL, renewing that lease (a time-bounded ownership lock) every 10 seconds while polling Trino for progress. If Instance A crashes or deploys: 1. Its lease expires within 30 seconds. 2. Instance B claims orphaned RUNNING rows whose lease_expires_at < now(), reads engine_query_id from PostgreSQL, and re-attaches to the running Trino query seamlessly. 3. Meanwhile, the user's browser polls GET /v1/statements/stmt_01J through any replica and never notices Instance A died.

    Direct-to-object-storage result spooling

    Routing a 100 GB export through the coordinator or API server would blow up memory. Instead: - Engine workers write compressed Arrow/Parquet/CSV chunks (~16–64 MB each) directly to s3://results/<tenant_id>/<statement_id>/part-0001.arrow (using Trino's spooled client protocol or CREATE TABLE / direct writer sink). - For small results (<= 10 MB, 99% of UI queries), the first chunk is also returned inline so dashboards render immediately. - For large exports, GET /result returns presigned URLs—temporary, cryptographically signed S3 links valid for 15 minutes—allowing the client SDK to download chunks in parallel at full S3 bandwidth straight from object storage. - Because result chunks copy sensitive tenant rows, they inherit per-tenant KMS encryption keys, strict tenant-checked presigning, GDPR erasure hooks, and an S3 24-hour bucket expiration rule.

    Cancellation and abandoned UI tabs

    • POST :cancel sets cancel_requested_at = now(); the lease owner aborts engine_query_id and transitions the row to CANCELED.
    • Canceling a MERGE before the catalog pointer swap leaves existing snapshots completely untouched (uncommitted files become harmless orphans cleaned up later); once the catalog swap succeeds, the commit is durable and POST :cancel returns the already-SUCCEEDED state.
    • Interactive queries whose UI client stops polling or listening to SSE for > 5 minutes auto-cancel to reclaim cluster slots, whereas mode = "batch" jobs run unattended up to their 6-hour quota.
  8. Deep dive 3: ACID writes, Copy-on-Write vs. Merge-on-Read, and concurrent writers

    Because Parquet files in object storage cannot be edited in place, Iceberg supports two strategies for UPDATE, DELETE, and MERGE:

    Strategy              How it updates 1 row in a 512 MB Parquet file        Best workload fit
    --------------------  ---------------------------------------------------  -------------------------------------
    Copy-on-Write (CoW)   Rewrites the entire 512 MB Parquet file minus/plus   Read-heavy analytics tables with
                          the changed row; commits new snapshot swapping file  infrequent bulk updates
    Merge-on-Read (MoR)   Leaves the 512 MB file untouched; writes a tiny      Frequent, scattered CDC merges or
                          delete file (file_path, row_pos) + small new data    GDPR deletes; background compaction
                          file; readers merge deletes on the fly               folds deletes in later
    

    Concrete example: a Merge updating 100,000 customer records scattered across 5,000 Parquet files (512 MB each) rewrites 5,000 × 512 MB ≈ 2.5 TB under Copy-on-Write, versus writing ~50 MB of position-delete/v3 deletion-vector files plus new rows under Merge-on-Read!

    Optimistic concurrency control (OCC) at the REST Catalog

    Because external streaming jobs and Spark clusters write to the same tables without talking to our service, an in-service lock cannot prevent write races. Instead, all writers coordinate through optimistic concurrency control (OCC) using an atomic compare-and-swap (CAS) on the catalog's metadata.json pointer:

    1. Query plans against base snapshot S10.
    2. Workers write new Parquet data/delete files + manifests + v11.metadata.json to S3 (invisible to all readers!).
    3. Coordinator calls Catalog.commit(table, expected_base=S10, new_metadata=v11).
    4. If no one else committed since S10, the catalog atomically updates the pointer to S11—done!
    5. If another writer already committed S11', CAS fails. Iceberg reloads S11' and validates whether the concurrent commit conflicts:
      • Pure concurrent INSERT appends never conflict: Iceberg rewrites only the tiny manifest list / metadata.json on top of S11' and retries CAS without rewriting a single Parquet file!
      • For MERGE/UPDATE/DELETE under Serializable isolation, validation checks whether S11' added files matching our read filter or modified/deleted the same data files we touched. If disjoint (for instance, two merges targeting different day partitions), metadata rebases cleanly; if overlapping, commit fails with CONCURRENT_MODIFICATION.

    Three service-level enhancements for rock-solid writes: - Per-table DML serialization queue: for writes submitted through our service to the same table, our Admission Controller runs one MERGE/UPDATE at a time so two users don't burn 2.5 TB of compute racing each other. - Automatic statement retry: if an external writer causes CONCURRENT_MODIFICATION, our service automatically re-plans and re-runs the DML statement from the latest snapshot (up to 3 retries with jitter). - Idempotent commit recovery via snapshot summary: we embed "statement_id": "stmt_01J..." inside Iceberg's snapshot summary map on every commit. If the catalog RPC times out right as the network blips, the recovery worker reloads the table's snapshot log and checks whether any snapshot carries stmt_01J...—proving with 100% certainty whether the write committed before retrying!

  9. Multi-tenant isolation, table maintenance, and scaling bottlenecks

    Data & compute isolation

    • Credential vending: Engine workers never hold a wildcard bucket IAM role; on each query, the Iceberg REST Catalog vends short-lived (1-hour) STS credentials scoped strictly to the authorized tenant's s3://warehouse/<tenant>/... table prefixes.
    • Separate compute pools + weighted fair queuing: Interactive, Batch, and Maintenance workloads run on separate worker pools (large enterprise tenants can opt into dedicated interactive clusters). When slots open on a shared interactive pool, weighted fair queuing picks the eligible tenant with the lowest active ratio running / fair_share_weight, breaking ties by oldest waiting query so idle tenants never starve behind earlier list entries:
    def pick_next_tenant(tenants: list):
        """Select the runnable tenant with the lowest weighted active share (FIFO tie-break)."""
        chosen_tenant = None
        chosen_key = None
    
        for tenant in tenants:
            if not tenant.queue or tenant.running >= tenant.max_running_interactive:
                continue
            weighted_share = tenant.running / tenant.fair_share_weight
            oldest_wait_ts = tenant.queue[0].submitted_at
            # Tuple comparison: lowest active share first, earliest queued timestamp on ties.
            candidate_key = (weighted_share, oldest_wait_ts)
            if chosen_key is None or candidate_key < chosen_key:
                chosen_tenant = tenant
                chosen_key = candidate_key
    
        return chosen_tenant
    

    Within the chosen tenant, a second round-robin sub-queue per user_id stops one analyst's 200-panel dashboard refresh from blocking every teammate in the same organization.

    Automated table maintenance (keeping queries fast week after week)

    table_health updates incrementally from snapshot summaries and triggers background jobs on the Maintenance Pool:

    Maintenance job          Problem it solves                               Trigger & safety rule
    -----------------------  ----------------------------------------------  -------------------------------------------
    Data compaction          Small streaming files + MoR delete accumulation Partition has > 50 files, avg < 64 MB, or
    (bin-pack + Z-order/sort)                                                > 10% deleted rows; skip last 1h hot data
    Rewrite manifests        Hundreds of tiny Avro manifests slow planning   > 100 manifests; cluster by partition range
    Expire snapshots         Reclaim storage from superseded Parquet files   Daily; default 7-day window + named tags
    Remove orphan files      Clean up uncommitted files from failed writes   Weekly; ONLY delete files > 3 days old!
    Prune metadata.json log  Prevent thousands of old metadata JSON files    write.metadata.previous-versions-max = 100
    

    Critical safety invariant on orphan cleanup: an in-flight 4-hour batch INSERT writes Parquet files that no snapshot references yet. Enforcing a strict >= 3-day age threshold on orphan deletion guarantees cleanup never deletes files belonging to a currently running statement!

    Scaling bottlenecks - Coordinator CPU/memory during planning: horizontally shard across multiple Trino clusters behind the Admission Controller and keep local SSD manifest caches warm. - S3 5,500 GET/s per-prefix throttling: enable Iceberg's object-storage file layout (write.object-storage.enabled=true), which prepends deterministic hashes to S3 paths so reads fan out across thousands of prefixes automatically. - Hot table scans: enable local NVMe SSD Parquet block caching (such as Alluxio/RubiX built into Trino) with consistent-hash split affinity so repeated reads of hot files hit local NVMe at > 5 GB/s instead of S3.

  10. Failure handling and trade-off summary

    Failure recovery summary

    Failure event                        Recovery behavior
    -----------------------------------  -----------------------------------------------------------------------
    Statement Service instance crashes   30 s lease expires; peer replica adopts row and re-attaches via query_id
    Interactive coordinator/worker dies  Service retries SELECT once on a healthy cluster pinned to the EXACT same
                                         snapshot_id; DML retries only after checking snapshot summary lacks id
    Batch worker spot-instance evicted   Spill-to-S3 fault-tolerant execution re-runs only the lost stage tasks
    Catalog timeout during DML commit    Inspect latest snapshots for summary["statement_id"] before any re-run
    REST Catalog outage                  DML fails safely; SELECT fails closed (or optional opt-in stale metadata)
    S3 503 Slow Down throttling          Jittered exponential backoff; triggers compaction + hash-prefix check
    Query exceeds 24h result retention   API returns 410 Gone with one-click re-run pinned to original snapshot_id
    

    Summary of key trade-offs

    • Wrapping Trino/Spark vs. building an engine: ships production SQL + Iceberg support in months instead of years, trading deep engine internals control for multi-cluster orchestration and admission routing.
    • Hybrid wait_timeout_s async statement API vs. pure sync or pure async: delivers single-round-trip speed for sub-second queries while preventing HTTP timeouts and enabling 100 GB resumable downloads for long jobs.
    • Direct worker-to-S3 result chunks + presigned URLs vs. streaming through API servers: eliminates API/coordinator memory bottlenecks at the cost of managing a 24-hour encrypted result bucket.
    • Copy-on-Write vs. Merge-on-Read per table: balances write amplification against read-time delete merging, backed by automated compaction so read speed never decays permanently.
    • Catalog CAS optimistic concurrency vs. centralized locks: works safely alongside external streaming and Spark writers without blocking readers, mitigated by per-table DML queuing inside our service.

Intuition & how it works

Picture Apache Iceberg as a giant cloud warehouse of sealed, read-only boxes (Parquet data files in object storage like Amazon S3) paired with a detailed library card catalog at the front desk, and picture our SQL service as a busy kitchen counter that hands you a numbered claim ticket (statement_id) instead of forcing you to stand frozen at the register while a banquet cooks. Every time someone changes a table, Iceberg never edits an existing box; it writes brand-new boxes, prints an updated catalog page (snapshot), and flips a single master bookmark in the Iceberg Catalog to point at the new page.

A naive service fails immediately for three reasons. First, opening every file in S3 to check which rows match WHERE takes over 30 minutes on a 200 TB table because each S3 request carries ~50–150 ms of network latency. Second, keeping one HTTP request open until SQL execution finishes breaks whenever a load balancer hits its 60-second idle timeout or a 50 GB export blows up server memory. Third, guarding UPDATE or MERGE with an in-memory lock inside our API server fails silently because external streaming pipelines and Spark jobs write directly to the same Iceberg tables through the catalog.

Here is how our design executes an analyst's query on a 200 TB, 2,000,000-file orders table step by step:

  1. Submit & claim ticket (t = 0 ms): The UI sends POST /v1/statements with SELECT region, SUM(amount) FROM orders WHERE order_ts >= '2026-11-01' AND order_ts < '2026-11-02' AND status = 'REFUNDED', an idempotency key (a unique client token preventing duplicate execution on retry), and wait_timeout_s = 5.
  2. Metadata-only pruning (t = 35 ms): Without opening a single Parquet data file, the planner reads the catalog's current snapshot pointer (S42), uses the manifest list's partition min/max ranges to skip 729 of 730 days, and checks cached manifest column bounds to drop files whose status range excludes 'REFUNDED'—shrinking 2,000,000 files (200 TB) down to 18 files (~1.8 GB) and projecting just the needed columns (~90 MB).
  3. Isolated parallel scan & direct spooling (t = 600 ms): The Admission Controller verifies the 90 MB scan fits the tenant's quota and dispatches splits to an Interactive Trino pool, whose workers scan the 18 files and write Arrow result chunks straight to S3 results/<tenant>/stmt_01J/.
  4. Fast hybrid delivery (t = 650 ms): Because execution finished inside the 5-second wait_timeout_s, POST immediately returns 200 OK with the rows and snapshot_id = S42 (whereas a 20-minute batch query returns 202 Accepted at 5 s so the client can poll progress and download chunks via presigned URLs—short-lived, signed S3 download links).

Key trade-offs

  • Wrapping an existing distributed SQL engine (Trino/Spark) vs. building one. Wrapping Trino for interactive queries and Fault-Tolerant Trino/Spark for batch gives mature SQL optimization, vectorized Parquet readers, and Iceberg support on day one, letting our team focus on multi-tenant isolation, statement lifecycle, and automated table maintenance. The trade-off is working around engine constraints—such as single-coordinator planning bottlenecks and imperfect in-process memory isolation—by routing across multiple clusters.
  • Hybrid wait_timeout_s statement resource vs. pure synchronous or pure polling API. Pure synchronous HTTP fails on long queries and network drops; pure asynchronous polling adds at least two network round trips to tiny 200 ms dashboard queries. Allowing POST /v1/statements to wait up to a few seconds before falling back to 202 Accepted gives fast queries single-round-trip latency and slow queries durable survivability.
  • Spooling results directly to object storage vs. streaming through API servers. Having workers write chunked Arrow/Parquet files straight to S3 scales seamlessly to 100 GB exports and lets any stateless replica serve page fetches. It adds one object-storage write hop and creates a 24-hour copy of tenant data requiring KMS encryption and lifecycle deletion, which we balance by also returning results <= 10 MB inline on page 1.
  • Copy-on-Write (CoW) vs. Merge-on-Read (MoR) for UPDATE/DELETE/MERGE. Copy-on-Write rewrites every touched Parquet file during the write so reads stay fast with zero delete merging, but updating scattered rows rewrites terabytes. Merge-on-Read writes tiny position-delete files (or Iceberg v3 deletion-vector bitmaps) so writes finish fast, shifting a merge cost onto reads until background compaction folds the deletes into fresh Parquet files.
  • Serializable vs. Snapshot isolation on concurrent DML. Serializable isolation rejects a MERGE if a concurrent writer appended new rows that might match the MERGE condition, guaranteeing strict serial equivalence at the cost of more retries on busy tables; Snapshot isolation lets concurrent appends proceed without conflict when they do not modify the same existing files. Defaulting to Serializable keeps financial/customer merges strictly safe while allowing table owners to opt down when appropriate.
  • Shared multi-tenant pools vs. dedicated tenant clusters. Shared clusters with weighted fair queuing (allocating open slots proportionally to tenant weights) maximize hardware utilization across hundreds of small tenants, while dedicated clusters provide hard memory and CPU isolation for the largest enterprise tenants.

Common mistakes

  • Scanning Parquet files to discover which rows match a filter, ignoring Iceberg's manifest-list partition summaries and manifest column min/max bounds—turning a sub-second 1-day query into a 33-minute full-table scan.
  • Forgetting to skip status == 'DELETED' tombstone entries when reading Iceberg manifests, causing a custom planner or metadata inspector to read already-compacted files and double-count rows.
  • Tying query execution to a single open HTTP connection, so load-balancer 60-second idle timeouts kill multi-minute queries and client network retries execute INSERT or MERGE statements twice.
  • Buffering large query results in API server or coordinator RAM, allowing a single user's 50 GB export to trigger an out-of-memory crash for every tenant on that node.
  • Using an in-memory lock inside the query service to coordinate table writes, which external Spark or Flink streaming writers bypass completely—always rely on the Iceberg catalog's atomic compare-and-swap (CAS) pointer update.
  • Blindly retrying a timed-out catalog commit without checking whether the first attempt landed, risking duplicate appends; embed statement_id in the Iceberg snapshot summary and inspect recent snapshots before retrying.
  • Caching a table's "current snapshot" pointer for minutes without asking the catalog, serving stale data after writes. Cache immutable manifest and Parquet files forever by path, never the mutable catalog pointer.
  • Deleting unreferenced "orphan" S3 files with no minimum age threshold, which deletes newly written Parquet files belonging to a long-running batch INSERT or MERGE before it commits its snapshot! Always require orphan files to be older than the maximum allowed query runtime (e.g., >= 3 days).

Follow-up questions

  • Suppose a streaming pipeline commits tiny batches to a table once per minute, causing query latency to degrade steadily week over week. What causes that slowdown, and how do you remediate it? Committing once per minute generates 60 × 24 × 7 = 10,080 snapshots alongside tens of thousands of small Parquet files and Avro manifests every week. Queries degrade during both planning and execution: the coordinator must fetch and parse thousands of fragmented manifests, object storage pays 50–150 ms of request overhead opening each tiny Parquet object instead of streaming contiguous blocks, and column min/max bounds across unsorted micro-files overlap heavily so file pruning loses effectiveness. Remediate this on two fronts: (1) schedule automated maintenance jobs that bin-pack partitions older than 1 hour into ~512 MB Parquet files sorted or Z-ordered on common filter keys, rewrite manifests into ~8 MB partition-aligned files, expire fine-grained streaming snapshots after 24–48 hours, and cap metadata.json version retention; and (2) adjust the streaming sink to micro-batch commits every 3–5 minutes from a single coordinator pre-shuffled by partition key.
  • How can the platform execute historical queries pinned to past table states, and what storage and compliance trade-offs arise from retaining older snapshots? Support SQL FOR VERSION AS OF <snapshot_id_or_tag> by resolving that snapshot entry directly in metadata.json, and FOR TIMESTAMP AS OF <ts> by selecting the latest snapshot whose timestamp_ms <= ts, then running the standard planning pipeline against that snapshot's manifest list paired with its recorded schema_id (so renamed or dropped columns match the historical schema). Storage overhead scales with write churn: pure append-only tables incur almost zero extra cost because historical snapshots reference a subset of current Parquet files, whereas a 10 TB table rewriting 3% of files daily via updates and compaction retains 10 TB × 3% × 30 = 9 TB of superseded files across a 30-day window. Furthermore, rows erased for privacy regulations (GDPR/CCPA) remain accessible via historical snapshots until every referencing snapshot is expired and cleaned up, so keep default retention shorter than deletion SLAs (e.g., 7 days) and reserve named Iceberg tags for audited checkpoints such as quarter-end close.
  • Design a result-caching mechanism that guarantees callers never receive outdated rows after table data or schemas change. Construct a deterministic cache lookup key from (normalized_sql_ast, [(table_fqn, current_snapshot_id, current_schema_id) for every base table after view expansion], row_filter_and_masking_policy_hash, session_timezone_and_settings, engine_version) and restrict caching to pure deterministic functions (excluding current_timestamp, random(), and external UDFs). On submission, perform one lightweight catalog lookup per referenced table to obtain its active snapshot_id and schema_id (including schema_id is essential because ALTER TABLE RENAME/ADD COLUMN advances metadata.json without producing a new data snapshot, which would otherwise alter SELECT * columns!). Because Iceberg snapshots are immutable, cached results keyed by (snapshot_id, schema_id) cannot go stale—every committed write or schema evolution changes the tuple and misses old cache entries automatically without explicit invalidation. To preserve cache hits when streaming writes append only to today's partition while queries read historical months, add an optional post-planning lookup keyed on the canonical digest of pruned data and delete file paths.
  • Walk through what occurs when two concurrent sessions submit MERGE statements targeting the same Iceberg table simultaneously. Suppose Session A and Session B both plan their MERGE operations against base snapshot S10 and write new Parquet data/delete files to object storage concurrently; neither write is visible to readers yet. Session A finishes first and wins the catalog's atomic compare-and-swap, advancing the table pointer from S10 to S11. When Session B attempts its swap expecting S10, the CAS check fails and triggers Iceberg's conflict validation across (S10 -> S11): if both statements carry partition predicates proving they touched disjoint partitions (for instance, Session A merged 2026-11-01 while Session B merged 2026-11-02), Iceberg rebases Session B's manifests onto S11 and commits S12 without re-executing data scans! If their target predicates overlap—or omit partition filters under Serializable isolation, or touch the same underlying data file—validation aborts Session B with CONCURRENT_MODIFICATION so neither mutation is ever silently clobbered; our Admission Controller prevents wasted compute for through-service writes by serializing per-table DML in a queue, and automatically re-plans and retries from S11 (with jittered backoff) if an external writer caused a conflict.

Follow-up questions

Similar questions

More Amperity interview questions

All 6 Amperity questions →