KatInterview

Async Query Client for a Cloud Data Warehouse

Data Structure DesignModel answer
MediumModel answerData Structure Designapi-designasyncerror-handling

Last 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_query must 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

  1. How would you store and rotate database credentials securely in a production service?
  2. 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.