Building a Multi-Tenant SQL Gateway on Iceberg Data Lakes
System DesignModel answerLast updated
Architect a hosted service that accepts SQL from a UI or API, plans and runs it against Iceberg tables on shared compute, and returns results while isolating tenants and handling writes.
You are asked to design a hosted platform where people write SQL and receive answers, and where every table lives in Apache Iceberg format on object storage. Users reach it through a browser console or a programmatic API. The platform takes each statement, executes it against the relevant Iceberg tables, and delivers the output.
Walk through your design as you would in a system design discussion. Before diving in, state which assumptions you would confirm, for example:
- Is the platform read-only, or must it also support
INSERT,UPDATE,DELETEandMERGE? - Are the workloads interactive, scheduled batch, or a mix, and what latency does each need?
- Is it multi-tenant, and how strongly must tenants be isolated in terms of load and data access?
- Do we write our own engine, or wrap an existing distributed engine?
- What are the expected concurrency, table sizes and result sizes?
- Which catalog manages the tables, and do other systems write to them too?
Your answer should address:
- The API and the lifecycle of a query: submit, poll status, cancel, and fetch results that may be very large.
- How planning uses the catalog, snapshots, manifests and column statistics to skip irrelevant files, and how a query sees one consistent view of a table.
- Distributed execution, scaling of workers, admission control and tenant isolation.
- Write and commit behavior, including what happens when two writers target the same table.
- Failure handling, authorization on tables and on storage, table maintenance, and observability for each query.
Hints
Hint 1
Pin the query's view of the table at planning time by resolving the table to a single snapshot ID, and carry that ID through every task. Think about what this buys you for retries and for repeatable results.
Hint 2
Iceberg metadata forms a tree: catalog pointer, metadata file, manifest list, manifests, data files. Each level carries statistics (partition ranges, column min/max, counts) that let the planner discard work before any data file is opened.
Hint 3
For writes, think optimistic concurrency: writers produce new files first, then atomically swap the catalog's metadata pointer. Consider what a loser of that race must do, and why row-level deletes and compaction add complications.
Hint 4
Separate the control plane (API, scheduler, planner, catalog access) from the data plane (stateless workers), and put a queue with per-tenant quotas in between so one tenant cannot starve others.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I would state these up front: the service supports both interactive reads and batch jobs, handles writes (INSERT, MERGE, DELETE) in a later phase, is multi-tenant, wraps an existing distributed engine (Trino or Spark style) rather than writing a new one, uses a REST catalog, and must tolerate other writers such as streaming ingest. Rough scale: hundreds of concurrent queries, tables of tens of TB with millions of files, interactive p50 of a few seconds.
Architecture
Control plane
- API gateway: authentication, rate limits, request validation.
- Query service: stores query state (queued, planning, running, finished, failed, cancelled) in a durable metadata store such as Postgres.
- Scheduler and admission controller: decides when and where a query runs.
- Coordinator/planner: parses SQL, resolves tables via the catalog, and builds the distributed plan.
Data plane
- Pools of stateless workers on autoscaled containers or VMs, reading from object storage (S3/GCS) and exchanging intermediate data between stages.
- Separate pools for interactive and batch traffic.
Query lifecycle and API
Execution is asynchronous because queries can run for minutes.
POST /querieswith SQL, default catalog/schema and session options returns aquery_idimmediately.GET /queries/{id}returns state, progress and error details.DELETE /queries/{id}cancels; the coordinator propagates cancellation to workers, which stop reading and release memory.GET /queries/{id}/results?page_token=...returns paged results.
For large results, do not stream everything through the API. Workers write result sets as Parquet or CSV to a per-query prefix in object storage, and the API returns paged rows for small results or signed URLs for large ones. Apply a result size cap, a TTL (for example 24 hours) and lifecycle rules for cleanup. Submissions carry an idempotency key so client retries do not start duplicate queries.
Planning with Iceberg metadata
- Authorize the user against the tables referenced.
- Ask the catalog for the current metadata location and pin one snapshot ID (or honor
FOR VERSION AS OF/FOR TIMESTAMP AS OF). All tasks of the query read that snapshot, so the result is consistent even while writers commit, and task retries are safe. - Read the manifest list and prune manifests using partition-range summaries.
- Read surviving manifests and prune data files using partition values and per-column min/max and null counts against the pushed-down predicates.
- Turn the remaining files into splits (about 128 MB each, large files split by row group) and distribute them.
Cache metadata aggressively: manifests are immutable, so they can be cached by path indefinitely. Parallelize manifest reads for tables with many manifests. Project only needed columns and push down filters to Parquet row-group and page level.
Execution and scaling
- Stage-based plan: scan, partial aggregate, shuffle, final aggregate, join, sort or limit.
- Joins: broadcast small sides, partitioned hash joins for large ones; spill to disk when memory is exceeded.
- Autoscale workers on queue depth and CPU; keep a warm minimum pool for interactive latency.
- Handle skew with split rebalancing and dynamic filtering.
- Retry failed tasks since inputs are immutable. For long batch queries, persist exchange data so a lost worker does not force a full restart.
Admission control and isolation
- Classify queries by cost estimate (bytes scanned after pruning) and by tenant.
- Per-tenant quotas on concurrent queries, memory and bytes scanned, with weighted fair queuing between tenants.
- Separate interactive and batch queues; large queries cannot occupy all interactive slots.
- Per-query limits: memory, wall-clock time, scanned bytes. Kill the offenders with a clear error.
- For hard isolation, give premium tenants dedicated worker pools.
Writes and commits
Iceberg commits are optimistic:
- Workers write new data files (and delete files for row-level changes) to storage; nothing is visible yet.
- The coordinator builds new manifests and a new metadata file, then asks the catalog to swap the table pointer from the base metadata to the new one, atomically.
- If another writer committed first, the swap fails. For appends, rebase onto the new snapshot and retry (cheap, no data rewrite). For
MERGE/DELETE, re-validate that the files this operation read were not changed by the winner; if they were, the operation fails or reruns.
Retry with backoff and a cap, and clean up orphaned files from failed attempts. Mind the small-file problem for frequent small inserts.
Failures
- Coordinator crash: query state is in the durable store; on restart, mark in-flight queries as failed or resume if the plan was checkpointed.
- Worker loss: reschedule its tasks.
- Catalog or storage throttling: backoff, request coalescing, prefix spreading.
- Clean up abandoned result files and uncommitted data files.
Security
- Authenticate users (SSO/OAuth) and enforce table, column and row-level permissions in the planner.
- Workers get short-lived, vended credentials scoped to the table paths the query needs, so a bug or malicious UDF cannot read other tenants' data.
- Encrypt in transit and at rest; audit-log every statement.
Table maintenance
Run background jobs, ideally as managed tasks of the platform:
- Compaction to merge small files and apply delete files.
- Snapshot expiration and orphan file removal, with a safe retention window longer than the longest running query.
- Manifest rewriting to keep planning fast.
- Optional clustering/sort ordering to improve pruning.
Observability
Per query: queue time, planning time (files considered vs. pruned), bytes scanned, rows, spill, per-stage timing, and error. Expose it in the UI with the plan and a history view. Track platform SLOs: queue wait p95, success rate, cache hit rate.
Common mistakes
- Doing planning without pinning a snapshot, producing inconsistent reads.
- Returning large results through the API process.
- A single shared queue with no tenant fairness.
- Expiring snapshots while queries still reference them.
- Treating commit conflicts as rare and not designing the retry/validate path.
- Giving workers broad storage credentials.
Trade-offs
Reusing an existing engine speeds delivery and gives mature optimizers, at the cost of less control over multi-tenancy; shared pools give better utilization, dedicated pools give better isolation and predictable latency. A mixed approach, shared by default and dedicated for large tenants, is usually the practical answer.