Async Query Client for a Cloud Data Warehouse
Data Structure DesignModel answerLast updated
Design and implement a lightweight client that submits async SQL queries, polls for status, retrieves results, and handles errors and credentials safely.
Background
Cloud data warehouses execute queries asynchronously. You submit a query, receive a handle, poll until it finishes, then fetch the results. A well-written client hides this lifecycle behind a clean interface, translates low-level SDK errors into actionable exceptions, and never exposes credentials.
Your Task
Implement a QueryClient class that wraps a mock warehouse SDK. The client must support the following operations:
connect() — authenticate with the warehouse using credentials supplied at construction. Fail immediately if credentials are missing or invalid, rather than discovering the problem on the first query.
start_query(sql, params) → query_id — submit a SQL statement with optional bound parameters and return a locally generated unique identifier. Parameters must be passed to the SDK for server-side binding; never interpolate them into the SQL string.
get_query_status(query_id) → state — return the current state of a query. Valid states are QUEUED, RUNNING, SUCCEEDED, FAILED, and CANCELED. Raise a clear error for unrecognized query IDs.
get_results(query_id) → rows — return the result rows for a completed query. Raise a descriptive error if the query has not yet succeeded, has failed, or was canceled.
cancel_query(query_id) — request cancellation of an in-progress query. Canceling a query that is already in a terminal state should be a no-op.
wait_for_results(query_id, timeout_s) → rows — poll get_query_status with exponential backoff until the query reaches a terminal state or the deadline expires, then return the rows. Cancel the server-side query if the deadline is exceeded so it stops consuming resources.
What the SDK provides
Assume you are given an object with this interface:
class WarehouseSDK(Protocol):
def authenticate(self, account: str, user: str, secret: str) -> str: ... # returns session token
def submit(self, token: str, sql: str, params: list, request_id: str) -> str: ... # returns server handle
def status(self, token: str, handle: str) -> tuple[str, str | None]: ... # (state_str, error_msg)
def fetch(self, token: str, handle: str) -> list[dict]: ...
def cancel(self, token: str, handle: str) -> None: ...
The SDK raises ConnectionError or TimeoutError for transient network problems, PermissionError for auth failures, ValueError for malformed SQL, and KeyError for unknown handles.
Requirements and constraints
- Translate every SDK exception into a domain-specific exception (
AuthenticationError,InvalidSQLError,TransientNetworkError, etc.) that callers can catch by type. - Retry transient network errors with exponential backoff and jitter, up to a configurable maximum. Never retry auth failures or invalid SQL.
- A retried
start_querymust not launch the same query a second time. Use an idempotency key. - The client must be safe to share across threads.
- Credentials must never appear in
repr, log output, or exception messages. - Local config validation (missing account, user, or secret) must raise at construction time, not at query time.
Follow-up questions
- How would you store and rotate database credentials securely in a production service?
- How would you extend the client to submit hundreds of queries in parallel and collect all their results efficiently?
Hints
Hint 1
Model query lifecycle as an explicit state machine. QUEUED and RUNNING are transient; SUCCEEDED, FAILED, and CANCELED are terminal. Every public method should check the state before doing network work — many errors can be caught locally without a round trip.
Hint 2
Use a UUID both as your public query_id and as the idempotency key passed to the SDK. This means a retried submit reuses the same key, so a well-behaved warehouse returns the original handle rather than starting a duplicate query. Store a local registry mapping your UUID to the server handle.
Hint 3
Separate retry logic into a single helper. Pass it a callable and let it decide whether to retry based on the exception type. Network errors get exponential backoff with random jitter; everything else propagates immediately. This keeps all other methods clean.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a design-in-code problem. The interviewer is evaluating whether you can build a thin, disciplined wrapper around an unreliable remote system — not whether you know Snowflake's API. Strong answers share four properties: fail-fast config validation, a typed error hierarchy, retry logic that distinguishes safe-to-retry from never-retry, and a clear state machine.
Design Decisions
Configuration and validation. Build a ClientConfig dataclass that raises ConfigurationError in __post_init__ if any required field is blank. Mark the secret field with field(repr=False) so it is excluded from repr and never appears in logs. Support loading from environment variables as a convenience.
Error hierarchy. Map every SDK exception to a domain type:
| SDK exception | Domain exception |
|---|---|
PermissionError | AuthenticationError |
ValueError | InvalidSQLError |
ConnectionError, TimeoutError | TransientNetworkError |
KeyError | UnknownQueryError |
| Terminal state mismatch | QueryNotReadyError, QueryFailedError |
Callers can catch QueryClientError for anything, or specific subtypes when they need to respond differently.
Retry helper. A single _with_retries(fn) method wraps a callable, catches TransientNetworkError, and sleeps base * 2^attempt + jitter before trying again. It re-raises immediately on any other exception. Exponential backoff with jitter avoids thundering herd if many clients hit the same issue simultaneously.
Idempotency. start_query generates a UUID before the first network call. That UUID is both the public query_id and the request_id passed to sdk.submit. If the call fails transiently and is retried, the same UUID is reused, so the warehouse sees a duplicate request ID and returns the existing handle rather than starting a second query.
Thread safety. A single threading.Lock guards both the session token and the query registry. Lock sections are short (dictionary reads and writes only) so contention is minimal.
wait_for_results deadline. Compute deadline = time.monotonic() + timeout_s once at the start. On each poll, check the remaining time before sleeping. On expiry, call cancel_query before raising QueryTimeoutError — this stops the warehouse from consuming credits on a query whose results will never be used.
Code
import os, random, threading, time, uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional, Protocol, Sequence
# ── State machine ──────────────────────────────────────────────────────────────
class QueryState(str, Enum):
QUEUED = "QUEUED"
RUNNING = "RUNNING"
SUCCEEDED = "SUCCEEDED"
FAILED = "FAILED"
CANCELED = "CANCELED"
@property
def is_terminal(self) -> bool:
return self in (QueryState.SUCCEEDED, QueryState.FAILED, QueryState.CANCELED)
# ── Domain exceptions ──────────────────────────────────────────────────────────
class QueryClientError(Exception): ...
class ConfigurationError(QueryClientError): ...
class AuthenticationError(QueryClientError): ...
class InvalidSQLError(QueryClientError): ...
class TransientNetworkError(QueryClientError): ...
class QueryTimeoutError(QueryClientError): ...
class UnknownQueryError(QueryClientError): ...
class QueryNotReadyError(QueryClientError): ...
class QueryFailedError(QueryClientError): ...
# ── SDK protocol (provided by the interviewer) ─────────────────────────────────
class WarehouseSDK(Protocol):
def authenticate(self, account: str, user: str, secret: str) -> str: ...
def submit(self, token: str, sql: str, params: list, request_id: str) -> str: ...
def status(self, token: str, handle: str) -> tuple[str, Optional[str]]: ...
def fetch(self, token: str, handle: str) -> list[dict]: ...
def cancel(self, token: str, handle: str) -> None: ...
# ── Configuration ──────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class ClientConfig:
account: str
user: str
secret: str = field(repr=False) # excluded from repr/logs
max_retries: int = 3
base_backoff_s: float = 0.2
def __post_init__(self):
missing = [k for k in ("account", "user", "secret") if not getattr(self, k)]
if missing:
raise ConfigurationError(f"missing required config: {', '.join(missing)}")
@classmethod
def from_env(cls, prefix: str = "WAREHOUSE_") -> "ClientConfig":
return cls(
account=os.environ.get(prefix + "ACCOUNT", ""),
user=os.environ.get(prefix + "USER", ""),
secret=os.environ.get(prefix + "SECRET", ""),
)
# ── Internal record ────────────────────────────────────────────────────────────
@dataclass
class _QueryRecord:
handle: str # server-side handle
state: QueryState = QueryState.QUEUED
error: Optional[str] = None
# ── Client ─────────────────────────────────────────────────────────────────────
class QueryClient:
def __init__(self, config: ClientConfig, sdk: WarehouseSDK) -> None:
self._cfg = config
self._sdk = sdk
self._token: Optional[str] = None
self._queries: dict[str, _QueryRecord] = {}
self._lock = threading.Lock()
# -- connection ------------------------------------------------------------
def connect(self) -> None:
"""Authenticate and store the session token. Raises AuthenticationError on bad credentials."""
try:
token = self._with_retries(
lambda: self._sdk.authenticate(
self._cfg.account, self._cfg.user, self._cfg.secret
)
)
except PermissionError as e:
raise AuthenticationError("authentication failed — check account and credentials") from e
with self._lock:
self._token = token
# -- public API ------------------------------------------------------------
def start_query(self, sql: str, params: Sequence[Any] = ()) -> str:
if not sql or not sql.strip():
raise InvalidSQLError("SQL must be a non-empty string")
query_id = str(uuid.uuid4()) # also used as the idempotency key
try:
handle = self._call(
lambda t: self._sdk.submit(t, sql, list(params), query_id)
)
except ValueError as e:
raise InvalidSQLError(f"server rejected SQL: {e}") from e
with self._lock:
self._queries[query_id] = _QueryRecord(handle=handle)
return query_id
def get_query_status(self, query_id: str) -> QueryState:
record = self._resolve(query_id)
if record.state.is_terminal:
return record.state # no network call needed
state_str, error_msg = self._call(lambda t: self._sdk.status(t, record.handle))
new_state = QueryState(state_str)
with self._lock:
record.state = new_state
record.error = error_msg
return new_state
def get_results(self, query_id: str) -> list[dict]:
record = self._resolve(query_id)
state = self.get_query_status(query_id)
if state == QueryState.SUCCEEDED:
return self._call(lambda t: self._sdk.fetch(t, record.handle))
if state in (QueryState.FAILED, QueryState.CANCELED):
raise QueryFailedError(
f"query ended with state {state.value}: {record.error or 'no detail'}"
)
raise QueryNotReadyError(f"query is still {state.value}")
def cancel_query(self, query_id: str) -> None:
record = self._resolve(query_id)
if record.state.is_terminal:
return # already done, nothing to do
self._call(lambda t: self._sdk.cancel(t, record.handle))
with self._lock:
record.state = QueryState.CANCELED
def wait_for_results(
self, query_id: str, timeout_s: float = 60.0
) -> list[dict]:
deadline = time.monotonic() + timeout_s
interval = self._cfg.base_backoff_s
while True:
state = self.get_query_status(query_id)
if state == QueryState.SUCCEEDED:
return self.get_results(query_id)
if state in (QueryState.FAILED, QueryState.CANCELED):
raise QueryFailedError(f"query ended with state {state.value}")
remaining = deadline - time.monotonic()
if remaining <= 0:
self.cancel_query(query_id) # stop wasting warehouse credits
raise QueryTimeoutError(
f"query {query_id} did not complete within {timeout_s}s"
)
sleep_for = min(interval, remaining)
time.sleep(sleep_for + random.uniform(0, sleep_for * 0.1))
interval = min(interval * 2, 30.0) # cap at 30 s
# -- internals -------------------------------------------------------------
def _resolve(self, query_id: str) -> _QueryRecord:
with self._lock:
record = self._queries.get(query_id)
if record is None:
raise UnknownQueryError(f"no query with id {query_id}")
return record
def _call(self, fn) -> Any:
"""Ensure connected, then call fn(token), mapping SDK errors to domain errors."""
with self._lock:
if self._token is None:
self._lock.release()
try:
self.connect()
finally:
self._lock.acquire()
token = self._token
try:
return self._with_retries(lambda: fn(token))
except KeyError as e:
raise UnknownQueryError("warehouse does not recognize that query handle") from e
def _with_retries(self, fn) -> Any:
last_exc: Optional[Exception] = None
for attempt in range(self._cfg.max_retries + 1):
try:
return fn()
except (ConnectionError, TimeoutError) as e:
last_exc = e
if attempt == self._cfg.max_retries:
break
backoff = self._cfg.base_backoff_s * (2 ** attempt)
jitter = random.uniform(0, backoff * 0.2)
time.sleep(backoff + jitter)
except Exception:
raise # non-transient: propagate immediately
raise TransientNetworkError("network error after retries") from last_exc
Complexity
start_query,get_query_status,cancel_query: O(1) local work plus at mostmax_retries + 1network calls each.wait_for_results: polling interval doubles up to a 30-second cap, so a query running for time T triggers roughly O(log(30/base) + T/30) status calls — far cheaper than fixed-interval polling.- Space: O(Q) for the registry across Q tracked queries.
Common Mistakes
Retrying everything. Invalid SQL and bad credentials should never be retried — they will never succeed. Only catch network-class exceptions in the retry loop.
Interpolating parameters. String-formatting user values into SQL opens SQL injection. Always pass params as a separate list to the SDK for server-side binding.
Leaking credentials. Using a plain string for the secret means it appears in repr, str, and often in tracebacks. field(repr=False) on a frozen dataclass prevents this.
Polling with a fixed interval. A fixed 1-second interval wastes calls for fast queries and blocks too long on slow ones. Exponential backoff with a cap handles both cases.
Follow-up: Secrets Management
In production, never bake credentials into config files or environment variables directly. Store them in a secrets manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager). Fetch the secret at startup, cache it with a TTL, and rotate by re-fetching on an AuthenticationError. The secret field in ClientConfig holds only the current value — the retrieval logic belongs in a separate SecretsProvider abstraction.
Follow-up: Batch Queries
Submit all queries first in a tight loop (each start_query is a single async call), collecting all query_ids. Then use a ThreadPoolExecutor or asyncio task group to poll them concurrently, each running wait_for_results. A shared semaphore limits concurrent in-flight status calls to avoid overwhelming the warehouse. Collect results as futures resolve, not sequentially.